// ==UserScript==
// @name          书签分组显示工具
// @namespace     http://tampermonkey.net/
// @version       1.3
// @description   读取并展示浏览器书签，按文件夹分组显示，支持转换为JSON格式规避审核
// @author        Claude
// @match         *://*/*
// @exclude-match *://*.quark.cn/*
// @exclude-match *://*.baidu.com/*
// @exclude-match *://*.qq.com/*
// @exclude-match *://*.woozooo.com/*
// @grant         GM_addStyle
// @grant         GM_registerMenuCommand
// @grant         GM_xmlhttpRequest
// @grant         GM_getValue
// @grant         GM_setValue
// @grant         GM_deleteValue
// @connect       www.google.com
// @connect       favicon.yandex.net
// @connect       icon.horse
// @connect       t3.gstatic.com
// @connect       t2.gstatic.com
// @icon          https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/%E4%B9%A6%E7%AD%BE%E5%88%86%E7%BB%84%E6%98%BE%E7%A4%BA%E5%B7%A5%E5%85%B7/bookmark.png
// @updateURL     https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/%E4%B9%A6%E7%AD%BE%E5%88%86%E7%BB%84%E6%98%BE%E7%A4%BA%E5%B7%A5%E5%85%B7/%E4%B9%A6%E7%AD%BE%E5%88%86%E7%BB%84%E6%98%BE%E7%A4%BA%E5%B7%A5%E5%85%B7.user.js
// ==/UserScript==

(function() {
    'use strict';

    // 检测当前网站是否是蓝奏云
    const isLanzouSite = () => {
        const hostname = window.location.hostname;
        // 添加woozooo.com域名判断，特别包含pc.woozooo.com和up.woozooo.com
        return hostname.includes('lanzou') ||
               hostname.includes('lanzoui') ||
               hostname.includes('lanzoux') ||
               hostname.includes('woozooo.com');  // 涵盖pc.woozooo.com和up.woozooo.com
    };

    // 检测当前网站是否是Gitee
    const isGiteeSite = () => {
        const hostname = window.location.hostname;
        return hostname.includes('gitee.com');
    };

    // 检测当前页面是否是视频播放器页面
    const isVideoPlayerSite = () => {
        try {
            // 检测视频元素
            const videoElements = document.querySelectorAll('video');
            const hasVideoElements = videoElements.length > 0;

            // 检测视频控制元素
            const hasVideoControls = document.querySelectorAll('.video-controls, .player-controls, .vjs-control-bar, .ytp-chrome-bottom, .bilibili-player-video-control, .control-bar, .video-controlbar, .video-controller, .dplayer-controller').length > 0;

            // 检测全屏按钮
            const hasFullscreenButton = document.querySelectorAll('.fullscreen-btn, .fullscreen, .fullscreen-button, .ytp-fullscreen-button, .bilibili-player-video-btn-fullscreen, [title*="全屏"], [aria-label*="全屏"]').length > 0;

            // 检测视频播放器容器
            const hasVideoContainer = document.querySelectorAll('.video-container, .player-container, .video-player, .bilibili-player, .ytp-player-content, .video-box, #player, #videoPlayer, .videoArea, .video-area').length > 0;

            // 检测视频进度条
            const hasProgressBar = document.querySelectorAll('.progress-bar, .progress, .vjs-progress-control, .ytp-progress-bar, .bilibili-player-video-progress').length > 0;

            // 检测视频相关的iframe
            const hasVideoIframes = Array.from(document.querySelectorAll('iframe')).some(iframe => {
                try {
                    const src = iframe.src.toLowerCase();
                    return src.includes('player') ||
                           src.includes('video') ||
                           src.includes('media') ||
                           src.includes('bilibili') ||
                           src.includes('youtube') ||
                           src.includes('youku') ||
                           src.includes('embed');
                } catch (e) {
                    return false;
                }
            });

            // 检测URL中的视频播放器相关关键词
            const url = window.location.href.toLowerCase();
            const isVideoURL = url.includes('player') ||
                               url.includes('video') ||
                               url.includes('watch') ||
                               url.includes('movie') ||
                               url.includes('film') ||
                               url.includes('play') ||
                               url.includes('live') ||
                               url.includes('tv') ||
                               url.includes('stream') ||
                               url.includes('episode') ||
                               url.includes('v=');

            // 特别检测视频相关URL参数
            const urlParams = new URLSearchParams(window.location.search);
            const hasVideoParams = urlParams.has('v') || urlParams.has('vid') || urlParams.has('video_id');

            // 检测特定元素ID
            const hasVideoElementId = document.getElementById('player') ||
                                     document.getElementById('video-player') ||
                                     document.getElementById('video_player') ||
                                     document.getElementById('videoPlayer') ||
                                     document.getElementById('bilibili-player');

            // 检测常见视频网站的域名
            const hostname = window.location.hostname.toLowerCase();
            const isVideoSite = hostname.includes('youtube') ||
                               hostname.includes('youku') ||
                               hostname.includes('bilibili') ||
                               hostname.includes('iqiyi') ||
                               hostname.includes('v.qq') ||
                               hostname.includes('netflix') ||
                               hostname.includes('mgtv') ||
                               hostname.includes('tudou') ||
                               hostname.includes('douyin') ||
                               hostname.includes('kuaishou') ||
                               hostname.includes('hulu') ||
                               hostname.includes('naver') ||
                               hostname.includes('pptv') ||
                               hostname.includes('sohu.com') ||
                               hostname.includes('acfun');

            // 检测HTML中的特定内容
            const bodyContent = document.body.innerHTML.toLowerCase();
            const hasVideoKeywords = bodyContent.includes('video player') ||
                                    bodyContent.includes('播放器') ||
                                    bodyContent.includes('播放视频') ||
                                    bodyContent.includes('视频播放');

            // 如果满足多个条件，则更大概率是视频播放器页面
            const videoFeatureCount = [
                hasVideoElements,
                hasVideoControls,
                hasFullscreenButton,
                hasVideoContainer,
                hasProgressBar,
                hasVideoIframes,
                isVideoURL,
                hasVideoParams,
                Boolean(hasVideoElementId),
                hasVideoKeywords
            ].filter(Boolean).length;

            // 针对图片中的案例特别检测：视频进度条和播放控制
            if (document.querySelectorAll('[class*="play-bar"], [class*="播放器"], [class*="playbar"], [class*="time-line"], [class*="时间线"], [class*="进度条"]').length > 0) {
                return true;
            }

            // 特别检测图片中可能存在的特定元素：时间显示、音量控制等
            if (document.querySelectorAll('[class*="time-display"], [class*="volume-control"], [class*="播放控制"], [class*="音量控制"], [class*="倍速"], .speed-selector, .play-btn, .pause-btn').length > 0) {
                return true;
            }

            // 检测页面上的视频时间显示格式(xx:xx格式)
            const timeRegex = /\d+:\d+/;
            const timeElements = Array.from(document.querySelectorAll('span, div, p')).filter(el => {
                const text = el.textContent?.trim();
                return text && timeRegex.test(text) && text.length <= 10; // 限制长度避免误判
            });

            if (timeElements.length > 0 && (hasVideoElements || hasVideoContainer)) {
                return true;
            }

            // 如果是纯视频元素，则认为是视频播放器
            if (hasVideoElements && videoElements[0].offsetWidth > 400) {
                return true;
            }

            // 如果明确是视频网站或者满足2个以上特征，则判定为视频页面
            return isVideoSite || (videoFeatureCount >= 2);
        } catch (e) {
            console.error('检测视频播放器页面时出错:', e);
            return false;
        }
    };

    // 在脚本开始时检测是否为Gitee网站，如果是则直接退出
    if (isGiteeSite()) {
        console.log('检测到Gitee网站，不执行脚本');
        return; // 直接退出脚本执行
    }

    // 在脚本开始时检测是否为视频播放器页面，如果是则直接退出
    if (isVideoPlayerSite()) {
        console.log('脚本初始化时检测到视频播放器页面，不执行脚本');
        return; // 直接退出脚本执行
    }

    // 特别针对蓝奏云的处理：如果是在iframe中，则不执行任何操作
    if (isLanzouSite()) {
        try {
            if (window.self !== window.top) {
                console.log('检测到处于蓝奏云iframe中，脚本不执行');
                return; // 直接退出脚本执行
            }
        } catch (e) {
            console.error('检测iframe状态失败:', e);
        }
    }

    // 添加样式
    GM_addStyle(`
        .bookmarks-group-container {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        .bookmarks-group {
            background-color: white;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            padding: 20px;
            max-width: 90%;
            max-height: 90vh;
            width: 900px;
            position: absolute;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            font-size: 14px;
            color: #333;
            letter-spacing: 0.2px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            text-rendering: optimizeLegibility;
        }

        .bookmarks-content-wrapper {
            display: flex;
            flex-grow: 1;
            height: calc(100% - 130px);
            overflow: hidden;
            position: relative;
            gap: 1px; /* 添加间隙 */
        }

        .bookmarks-left-panel {
            width: 240px;
            flex-shrink: 0;
            border-right: 1px solid #eee;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            background-color: #f9f9f9;
            position: relative;
        }

        .bookmarks-right-panel {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
        }

        .bookmarks-category-list {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 5px;
            scrollbar-width: thin;
            scrollbar-color: #c1c1c1 #f1f1f1;
        }

        #bookmarks-container-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding-right: 10px;
            scrollbar-width: thin;
            scrollbar-color: #c1c1c1 #f1f1f1;
            padding-left: 0;
            padding-right: 0;
        }

        .bookmarks-category-item {
            padding: 10px 12px;
            margin: 0;
            cursor: pointer;
            font-weight: 500;
            color: #333;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: flex-start; /* 改为顶部对齐 */
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.5;
            transition: background-color 0.2s;
        }

        .bookmarks-category-item:hover {
            background-color: #f0f0f0;
        }

        .bookmarks-category-item.active {
            background-color: #e8f0fe;
            color: #0066cc;
            font-weight: 600;
        }

        .bookmarks-group-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 24px;
            margin-bottom: 15px;
            position: relative;
        }

        .bookmarks-group-header h3 {
            margin: 0;
            font-size: 22px;
            font-weight: 600;
            color: #222;
            letter-spacing: 0.3px;
        }

        .bookmarks-toolbar {
            padding: 0 0 15px 0;
            margin: 0 24px 15px 24px;
            border-bottom: 1px solid #eee;
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
            box-sizing: border-box;
        }

        .bookmarks-group-close {
            cursor: pointer;
            font-weight: bold;
            font-size: 24px;
            color: #666;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 15px;
            border-radius: 4px;
            transition: all 0.2s ease;
            margin-right: -10px;
        }

        .bookmarks-group-close:hover {
            background-color: rgba(0, 0, 0, 0.1);
            color: #333;
        }

        .bookmarks-content-wrapper {
            display: flex;
            flex-grow: 1;
            height: calc(100% - 130px);
            overflow: hidden;
            position: relative;
            gap: 1px; /* 添加间隙 */
        }

        .bookmarks-left-panel {
            width: 240px; /* 进一步增加宽度 */
            border-right: 1px solid #eee;
            overflow-y: auto;
            max-height: calc(80vh - 150px);
            padding: 0;
            background-color: #f9f9f9;
            flex-shrink: 0;
            box-sizing: border-box;
            position: relative;
            scrollbar-width: thin;
            scrollbar-color: #c1c1c1 #f1f1f1;
        }

        .bookmarks-right-panel {
            flex: 1;
            padding-left: 24px;
            padding-right: 24px;
            overflow-y: hidden;
            max-height: calc(80vh - 150px); /* 调整高度防止溢出 */
            display: flex;
            flex-direction: column;
            box-sizing: border-box; /* 确保padding不增加宽度 */
        }

        /* 自定义滚动条样式 */
        .bookmarks-left-panel::-webkit-scrollbar,
        .bookmarks-right-panel::-webkit-scrollbar,
        #bookmarks-container-content::-webkit-scrollbar,
        .bookmarks-search-results::-webkit-scrollbar,
        .bookmarks-category-list::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        .bookmarks-left-panel::-webkit-scrollbar-track,
        .bookmarks-right-panel::-webkit-scrollbar-track,
        #bookmarks-container-content::-webkit-scrollbar-track,
        .bookmarks-search-results::-webkit-scrollbar-track,
        .bookmarks-category-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .bookmarks-left-panel::-webkit-scrollbar-thumb,
        .bookmarks-right-panel::-webkit-scrollbar-thumb,
        #bookmarks-container-content::-webkit-scrollbar-thumb,
        .bookmarks-search-results::-webkit-scrollbar-thumb,
        .bookmarks-category-list::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .bookmarks-left-panel::-webkit-scrollbar-thumb:hover,
        .bookmarks-right-panel::-webkit-scrollbar-thumb:hover,
        #bookmarks-container-content::-webkit-scrollbar-thumb:hover,
        .bookmarks-search-results::-webkit-scrollbar-thumb:hover,
        .bookmarks-category-list::-webkit-scrollbar-thumb:hover {
            background: #a0a0a0;
        }

        .bookmarks-category-list {
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%;
            overflow-y: auto;
            box-sizing: border-box;
            padding-right: 4px; /* 增加右侧内边距 */
            padding-bottom: 20px; /* 添加底部内边距，确保最后一项完全显示 */
        }

        .bookmarks-category-item {
            padding: 10px 12px;
            margin: 0;
            cursor: pointer;
            font-weight: normal;
            color: #333;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: flex-start; /* 改为顶部对齐 */
            font-size: 13px;
            word-break: break-all;
            width: 100%;
            box-sizing: border-box;
            white-space: normal;
            line-height: 1.4;
            min-height: 40px;
            gap: 8px; /* 使用gap替代margin，更好的间距控制 */
        }

        .bookmarks-category-item .folder-text {
            flex: 1;
            min-width: 0; /* 防止flex项目溢出 */
            overflow-wrap: break-word; /* 更好的文字换行 */
            padding-right: 4px;
            font-weight: 500;
        }

        .bookmarks-category-item .folder-count {
            flex-shrink: 0;
            color: #666;
            font-size: 12px;
            padding-top: 2px; /* 稍微下移计数，对齐文本 */
            white-space: nowrap; /* 防止数字换行 */
            font-weight: 500;
        }

        .folder-icon {
            margin-right: 0; /* 移除margin，使用gap控制间距 */
            min-width: 16px;
            width: 16px; /* 确保固定宽度 */
            height: 16px;
            display: inline-block;
            color: #555;
            flex-shrink: 0;
            padding-top: 2px; /* 稍微下移图标，对齐文本 */
        }

        /* 修复滚动条样式 */
        .bookmarks-left-panel::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        .bookmarks-left-panel::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .bookmarks-left-panel::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        .bookmarks-left-panel::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 确保内容区域正确显示 */
        .bookmarks-content-wrapper {
            display: flex;
            flex-grow: 1;
            height: calc(100% - 130px);
            overflow: hidden;
            position: relative;
            gap: 1px; /* 添加间隙 */
        }

        .bookmarks-category-item:hover {
            background-color: #f0f0f0;
        }

        .bookmarks-category-item.active {
            background-color: #e8f0fe;
            color: #0066cc;
            font-weight: bold;
        }

        .bookmarks-group-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 12px;
            color: #222;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }

        .bookmarks-export-btn {
            font-size: 14px;
            font-weight: 600;
            padding: 6px 12px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            color: #333;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            transition: all 0.2s ease;
        }

        .bookmarks-export-btn:hover {
            background-color: #e8e8e8;
            box-shadow: 0 2px 3px rgba(0,0,0,0.1);
            border-color: #ccc;
        }

        .bookmarks-folder {
            margin-bottom: 15px;
        }

        .bookmarks-folder-title {
            font-weight: 600;
            font-size: 16px;
            margin: 8px 0;
            padding: 5px 0;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            color: #333;
        }

        .bookmarks-folder-title:hover {
            color: #1a73e8;
        }

        .bookmarks-folder-content {
            display: none;
            margin-left: 15px;
        }

        .bookmarks-folder-content.open {
            display: block;
        }

        .bookmarks-item {
            margin: 5px 0;
            padding: 5px 0;
            white-space: normal;
            word-break: break-word;
        }

        .bookmarks-item a {
            color: #333;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            max-width: 100%;
            white-space: normal;
            word-break: break-word;
            padding: 3px 0;
        }

        .bookmarks-item a:hover {
            text-decoration: underline;
            color: #1a73e8;
        }

        .bookmarks-toggle {
            font-size: 12px;
        }

        .no-access-message {
            text-align: center;
            margin: 50px auto;
            padding: 20px;
            max-width: 500px;
            background-color: #f8f8f8;
            border: 1px solid #eee;
            border-radius: 5px;
        }

        .no-access-message h4 {
            color: #d32f2f;
            margin-top: 0;
        }

        .import-btn {
            display: block;
            margin: 20px auto;
            padding: 10px 20px;
            background-color: #1a73e8;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .import-btn:hover {
            background-color: #0d5bdd;
        }

        .bookmarks-toolbar-btn {
            display: flex;
            align-items: center;
            padding: 6px 12px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: #333;
            transition: all 0.2s ease;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            height: 18px;
        }

        .bookmarks-toolbar-btn:hover {
            background-color: #e8e8e8;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-color: #ccc;
        }

        .bookmarks-toolbar-btn svg {
            margin-right: 6px;
            width: 14px;
            height: 14px;
        }

        .bookmarks-import-modal {
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            background-color: white !important;
            border-radius: 8px !important;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3) !important;
            padding: 24px !important;
            max-width: 500px !important;
            width: 90% !important;
            z-index: 10000 !important;
        }

        .bookmarks-import-modal h3 {
            margin: 0 0 20px 0 !important;
            padding: 0 0 15px 0 !important;
            font-size: 20px !important;
            font-weight: 600 !important;
            color: #202124 !important;
            border-bottom: 1px solid #e0e0e0 !important;
            display: block !important;
            width: 100% !important;
            text-align: left !important;
            letter-spacing: 0.3px !important;
        }

        .bookmarks-import-form {
            margin-bottom: 24px !important;
        }

        .bookmarks-tab-options {
            display: flex !important;
            gap: 24px !important;
            margin-bottom: 20px !important;
            border-bottom: 1px solid #e0e0e0 !important;
        }

        .bookmarks-tab-option {
            padding: 8px 4px !important;
            cursor: pointer !important;
            position: relative !important;
            color: #5f6368 !important;
            font-size: 14px !important;
            transition: all 0.2s !important;
        }

        .bookmarks-tab-option.active {
            color: #1a73e8 !important;
            font-weight: 500 !important;
        }

        .bookmarks-tab-option.active:after {
            content: '' !important;
            position: absolute !important;
            bottom: -1px !important;
            left: 0 !important;
            right: 0 !important;
            height: 2px !important;
            background-color: #1a73e8 !important;
        }

        .bookmarks-import-btns {
            display: flex !important;
            justify-content: flex-end !important;
            gap: 12px !important;
            margin-top: 24px !important;
        }

        .bookmarks-import-btn {
            padding: 8px 16px !important;
            border-radius: 4px !important;
            font-size: 14px !important;
            cursor: pointer !important;
            transition: all 0.2s !important;
        }

        .bookmarks-import-confirm {
            background-color: #1a73e8 !important;
            color: white !important;
            border: none !important;
        }

        .bookmarks-import-confirm:hover {
            background-color: #1557b0 !important;
        }

        .bookmarks-import-cancel {
            background-color: white !important;
            color: #5f6368 !important;
            border: 1px solid #dadce0 !important;
        }

        .bookmarks-import-cancel:hover {
            background-color: #f8f9fa !important;
        }

        /* 设置界面特定样式 */
        .settings-section {
            margin-bottom: 24px !important;
        }

        .settings-item {
            display: flex !important;
            justify-content: space-between !important;
            align-items: flex-start !important;
            margin-bottom: 20px !important;
        }

        .settings-label {
            flex: 1 !important;
            padding-right: 20px !important;
        }

        .settings-title {
            font-weight: 500 !important;
            color: #202124 !important;
            margin-bottom: 4px !important;
            font-size: 14px !important;
        }

        .settings-description {
            color: #5f6368 !important;
            font-size: 12px !important;
            line-height: 1.4 !important;
        }

        .bookmarks-search-container {
            display: flex;
            align-items: center;
            margin-left: auto;
            position: relative;
            width: 240px;
            max-width: 100%;
            height: 36px;
            transition: width 0.3s ease;
            border-radius: 18px;
            background-color: #f5f5f5;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            border: 1px solid #e0e0e0;
        }

        .bookmarks-search-container:hover,
        .bookmarks-search-container:focus-within {
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.12);
            width: 280px;
            border-color: #1a73e8;
        }

        .bookmarks-search-input {
            border: none;
            border-radius: 18px;
            padding: 8px 32px 8px 36px;
            width: 100%;
            height: 100%;
            font-size: 14px;
            font-weight: 500;
            color: #000;
            background-color: transparent;
            outline: none;
            box-sizing: border-box;
            transition: all 0.2s ease;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            letter-spacing: 0.2px;
        }

        .bookmarks-search-input::placeholder {
            color: #555;
            opacity: 0.8;
            font-weight: 400;
        }

        .bookmarks-search-input:focus {
            color: #000;
        }

        .bookmarks-search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #555;
            width: 16px;
            height: 16px;
            pointer-events: none;
            z-index: 1;
            opacity: 0.8;
        }

        .bookmarks-search-container:focus-within .bookmarks-search-icon {
            color: #1a73e8;
            opacity: 1;
        }

        /* 导入书签选项卡样式 */
        .bookmarks-tab-options {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 15px;
            gap: 20px; /* 增加选项卡之间的间距 */
        }

        .bookmarks-tab-option {
            padding: 10px 0;
            cursor: pointer;
            position: relative;
            user-select: none;
            color: #666;
            font-size: 14px;
            min-width: 80px; /* 确保选项卡有最小宽度 */
            text-align: center;
        }

        .bookmarks-tab-option.active {
            color: #1a73e8;
            font-weight: 500;
        }

        .bookmarks-tab-option.active:after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #1a73e8;
        }

        .bookmarks-tab-content {
            padding: 15px 0;
            display: none;
        }

        .bookmarks-tab-content.active {
            display: block;
        }

        #remote-tab-content {
            display: none;
            padding: 10px 0;
        }

        #remote-tab-content.active {
            display: block;
        }

        #local-tab-content {
            display: none;
            padding: 10px 0;
        }

        #local-tab-content.active {
            display: block;
        }

        .bookmarks-import-url {
            width: 100%;
            padding: 8px 12px;
            margin: 5px 0 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 14px;
            display: block;
        }

        .bookmarks-import-url:focus {
            border-color: #1a73e8;
            outline: none;
            box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
        }

        .bookmarks-search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 3px 12px rgba(0, 0, 0, 0.2);
            max-height: 300px;
            overflow-y: auto;
            z-index: 10001;
            margin-top: 8px;
            display: none;
            width: 320px;
            max-width: 90vw;
            pointer-events: auto;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #c1c1c1 #f1f1f1;
        }

        /* 自定义搜索结果滚动条样式 */
        .bookmarks-search-results::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        .bookmarks-search-results::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .bookmarks-search-results::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .bookmarks-search-results::-webkit-scrollbar-thumb:hover {
            background: #a0a0a0;
        }

        .bookmarks-search-no-result {
            padding: 20px 15px;
            text-align: center;
            color: #444;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.5;
            background-color: #f8f9fa;
            border-radius: 4px;
            margin: 10px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .bookmarks-search-result-item {
            padding: 10px 12px;
            border-bottom: 1px solid #e0e0e0;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: background-color 0.15s;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            text-rendering: optimizeLegibility;
        }

        .bookmarks-search-result-item:last-child {
            border-bottom: none;
        }

        .bookmarks-search-result-item:hover {
            background-color: #e8f0fe;
        }

        .bookmarks-search-result-icon {
            margin-right: 10px;
            width: 16px;
            height: 16px;
            flex-shrink: 0;
            object-fit: contain;
            border-radius: 2px;
        }

        .bookmarks-search-result-title {
            flex-grow: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-weight: 500;
            font-size: 14px;
            color: #000;
            line-height: 1.4;
            letter-spacing: 0.2px;
        }

        .bookmarks-search-result-folder {
            color: #1a73e8;
            font-size: 12px;
            margin-left: 8px;
            white-space: nowrap;
            font-weight: 500;
            padding: 2px 6px;
            background-color: #e8f0fe;
            border-radius: 4px;
        }

        .bookmarks-search-close {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #5f6368;
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            display: none;
            opacity: 0.7;
            transition: all 0.2s ease;
            border-radius: 50%;
            background-color: transparent;
            z-index: 1;
        }

        .bookmarks-search-close:hover {
            background-color: rgba(0, 0, 0, 0.05);
            color: #202124;
            opacity: 1;
        }

        /* 悬浮按钮样式 */
        .bookmarks-float-btn {
            position: fixed;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            background-color: rgba(26, 115, 232, 0.8);
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 0 4px 4px 0;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            z-index: 9998;
            transition: all 0.3s ease;
        }

        .bookmarks-float-btn:hover {
            background-color: rgba(26, 115, 232, 1);
            width: 45px;
        }

        .bookmarks-float-btn.hidden {
            left: -35px;
        }

        .bookmarks-float-btn svg {
            width: 24px;
            height: 24px;
        }

        #bookmarks-container-content {
            flex-grow: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding-right: 5px;
            height: calc(100% - 35px);
            scrollbar-width: thin;
            -webkit-overflow-scrolling: touch;
            box-sizing: border-box; /* 确保padding不增加宽度 */
        }

        /* 修复右侧书签滚动问题 */
        #bookmarks-container-content {
            scroll-behavior: auto !important;
            overflow: auto !important; /* 确保滚动可用 */
            pointer-events: auto !important; /* 确保鼠标事件有效 */
            position: relative !important; /* 确保正确的层叠关系 */
        }

        /* 确保内容区域的滚动可以正常工作 */
        .bookmarks-right-panel {
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
            position: relative !important;
        }
    `);

    // 用于存储设置的键名
    const SETTINGS_KEY = 'bookmarksToolSettings';
    // 用于存储书签的键名
    const BOOKMARKS_KEY = 'userBookmarks';
    // 用于存储书签备份的键名
    const BOOKMARKS_BACKUP_KEY = 'userBookmarksBackup';
    // 用于存储上次保存时间的键名
    const LAST_SAVE_TIME_KEY = 'lastBookmarksSaveTime';
    // 书签备份间隔时间（毫秒），默认1天
    const BACKUP_INTERVAL = 24 * 60 * 60 * 1000;
    // 全局悬浮按钮状态键（不区分域名，确保全局唯一）
    const GLOBAL_FLOAT_BTN_STATUS_KEY = 'globalFloatBtnStatus';
    // 按钮创建时间记录键
    const FLOAT_BTN_TIMESTAMP_KEY = 'floatBtnTimestamp';
    // 按钮过期时间(毫秒)
    const FLOAT_BTN_EXPIRE_TIME = 1000 * 60 * 5; // 5分钟

    // 默认设置
    const defaultSettings = {
        floatButtonEnabled: true,  // 悬浮按钮是否启用
        autoHideDelay: 3000,       // 自动隐藏延迟（毫秒）
        enableBackup: true,        // 是否启用自动备份
        backupInterval: BACKUP_INTERVAL // 备份间隔时间
    };

    // 加载设置
    function loadSettings() {
        try {
            // 尝试从GM_getValue获取设置(全局设置)
            let savedSettings = GM_getValue(SETTINGS_KEY);
            return savedSettings ? {...defaultSettings, ...savedSettings} : defaultSettings;
        } catch (error) {
            console.error('加载设置失败:', error);
            return defaultSettings;
        }
    }

    // 保存设置
    function saveSettings(settings) {
        try {
            // 直接保存到GM_setValue(全局存储)
            GM_setValue(SETTINGS_KEY, settings);
        } catch (error) {
            console.error('保存设置失败:', error);
        }
    }

    // 当前设置
    let settings = loadSettings();

    // 定义默认图标
    const DEFAULT_FAVICON = '';

    // 图标缓存对象
    const iconCache = {};

    // 定义缓存键名
    const ICON_CACHE_KEY = 'bookmarksIconCache';

    // 加载持久化的图标缓存
    function loadIconCache() {
        try {
            const cachedIcons = GM_getValue(ICON_CACHE_KEY);
            if (cachedIcons && typeof cachedIcons === 'object') {
                // 合并到内存缓存中
                Object.assign(iconCache, cachedIcons);
                console.log(`从存储加载了${Object.keys(cachedIcons).length}个图标缓存`);
            }
        } catch (error) {
            console.error('加载图标缓存失败:', error);
        }
    }

    // 保存图标缓存到持久化存储
    function saveIconCache(domain, iconUrl) {
        try {
            // 更新内存缓存
            iconCache[domain] = iconUrl;

            // 获取当前存储的缓存
            let cachedIcons = GM_getValue(ICON_CACHE_KEY, {});

            // 更新缓存
            cachedIcons[domain] = iconUrl;

            // 如果缓存过大，清理一部分较早的缓存
            const maxCacheEntries = 500; // 最大缓存条目数
            const domains = Object.keys(cachedIcons);

            if (domains.length > maxCacheEntries) {
                // 移除最早的1/4缓存条目
                const removeCount = Math.floor(domains.length / 4);
                const domainsToRemove = domains.slice(0, removeCount);

                domainsToRemove.forEach(d => {
                    delete cachedIcons[d];
                });

                console.log(`缓存过大，已清理${removeCount}个较早的图标缓存`);
            }

            // 保存回持久化存储
            GM_setValue(ICON_CACHE_KEY, cachedIcons);
        } catch (error) {
            console.error('保存图标缓存失败:', error);
        }
    }

    // 初始加载图标缓存
    loadIconCache();

    // 添加获取网页图标的函数，支持多种icon类型
    function getPageIconUrls(url) {
        return new Promise((resolve) => {
            try {
                if (!url || typeof url !== 'string') {
                    resolve([DEFAULT_FAVICON]);
                    return;
                }

                // 处理非URL格式的链接
                if (!url.startsWith('http') && !url.startsWith('https')) {
                    resolve([DEFAULT_FAVICON]);
                    return;
                }

                const urlObj = new URL(url);
                const domain = urlObj.hostname;
                if (!domain) {
                    resolve([DEFAULT_FAVICON]);
                    return;
                }

                // 先尝试使用XMLHttpRequest请求页面HTML，然后解析其中的图标链接
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: url,
                    timeout: 5000,
                    onload: function(response) {
                        try {
                            if (response.status !== 200) {
                                throw new Error('请求失败');
                            }

                            // 使用DOMParser解析HTML
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(response.responseText, 'text/html');

                            // 查找所有可能的图标链接元素
                            const iconLinks = [];

                            // 查找link元素中的图标
                            const linkElements = doc.querySelectorAll('link[rel*="icon"]');
                            linkElements.forEach(link => {
                                const href = link.getAttribute('href');
                                if (href) {
                                    // 处理相对路径
                                    const absoluteUrl = new URL(href, url).href;
                                    iconLinks.push(absoluteUrl);
                                }
                            });

                            // 查找meta标签中的图标
                            const metaElements = doc.querySelectorAll('meta[property="og:image"], meta[name="twitter:image"]');
                            metaElements.forEach(meta => {
                                const content = meta.getAttribute('content');
                                if (content) {
                                    // 处理相对路径
                                    const absoluteUrl = new URL(content, url).href;
                                    iconLinks.push(absoluteUrl);
                                }
                            });

                            // 添加标准图标位置
                            iconLinks.push(`https://${domain}/favicon.ico`);
                            iconLinks.push(`https://${domain}/favicon.png`);
                            iconLinks.push(`https://${domain}/apple-touch-icon.png`);

                            // 添加备用服务提供的图标
                            iconLinks.push(`https://favicon.yandex.net/favicon/${domain}`);
                            iconLinks.push(`https://icon.horse/icon/${domain}`);
                            iconLinks.push(`https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=https://${domain}&size=32`);

                            // 最后添加默认图标，确保始终有至少一个图标
                            iconLinks.push(DEFAULT_FAVICON);

                            // 返回去重后的图标链接数组
                            resolve([...new Set(iconLinks)]);

                        } catch (error) {
                            console.error('解析页面获取图标失败:', error);
                            // 出错时返回备用图标列表
                            resolve(getFaviconUrl(url));
                        }
                    },
                    onerror: function() {
                        // 请求失败时使用备用方法
                        resolve(getFaviconUrl(url));
                    },
                    ontimeout: function() {
                        // 请求超时时使用备用方法
                        resolve(getFaviconUrl(url));
                    }
                });

            } catch (error) {
                console.error('获取页面图标出错:', error);
                resolve([DEFAULT_FAVICON]);
            }
        });
    }

    // 修改getFaviconUrl函数，优化图标获取
    function getFaviconUrl(url) {
        try {
            if (!url) return [DEFAULT_FAVICON];

            // 处理非URL格式的链接（如javascript:、about:等）
            if (!url.startsWith('http') && !url.startsWith('https') && !url.startsWith('ftp')) {
                return [DEFAULT_FAVICON];
            }

            const urlObj = new URL(url);
            const domain = urlObj.hostname;

            if (!domain) return [DEFAULT_FAVICON];

            // 使用多种备用图标源
            return [
                // 域名直接图标
                `https://${domain}/favicon.ico`,
                `https://${domain}/favicon.png`,
                // Google提供的图标服务
                `https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=https://${domain}&size=32`,
                // Yandex图标服务
                `https://favicon.yandex.net/favicon/${domain}`,
                // Icon Horse服务
                `https://icon.horse/icon/${domain}`,
                // 默认图标
                DEFAULT_FAVICON
            ];
        } catch (e) {
            console.error('URL解析失败:', e, url);
            return [DEFAULT_FAVICON];
        }
    }

    // 修改createFaviconElement函数，优化图标加载
    function createFaviconElement(url) {
        const iconElement = document.createElement('img');
        iconElement.style.width = '16px';
        iconElement.style.height = '16px';
        iconElement.style.marginRight = '8px';
        iconElement.style.verticalAlign = 'middle';
        iconElement.style.objectFit = 'contain'; // 确保图标完整显示

        // 默认先显示加载中的占位符或默认图标
        iconElement.src = DEFAULT_FAVICON;

        // 无效URL直接使用默认图标
        if (!url || !(url.startsWith('http') || url.startsWith('https'))) {
            return iconElement;
        }

        try {
            // 从URL中提取域名
            const domain = new URL(url).hostname;

            // 检查缓存中是否已有该域名的图标
            if (iconCache[domain]) {
                iconElement.src = iconCache[domain];
                return iconElement;
            }

            // 尝试从页面获取图标URL
            getPageIconUrls(url).then(iconUrls => {
                if (!iconUrls || iconUrls.length === 0) {
                    iconElement.src = DEFAULT_FAVICON;
                    return;
                }

                // 创建Image对象用于预加载
                const img = new Image();
                let currentIndex = 0;

                // 设置错误处理
                img.onerror = function() {
                    currentIndex++;
                    if (currentIndex < iconUrls.length) {
                        img.src = iconUrls[currentIndex];
                    } else {
                        iconElement.src = DEFAULT_FAVICON;
                        saveIconCache(domain, DEFAULT_FAVICON); // 使用持久化缓存
                    }
                };

                // 设置成功加载处理
                img.onload = function() {
                    iconElement.src = img.src;
                    saveIconCache(domain, img.src); // 使用持久化缓存
                };

                // 开始加载第一个图标
                img.src = iconUrls[0];
            });

            // 设置备用错误处理
            iconElement.onerror = function() {
                this.src = DEFAULT_FAVICON;
                this.onerror = null; // 防止无限循环
            };

        } catch (e) {
            console.error('图标加载失败:', e);
            iconElement.src = DEFAULT_FAVICON;
        }

        return iconElement;
    }

    // 创建悬浮按钮
    function createFloatButton() {
        // 检测是否是视频播放器页面，如果是则不创建悬浮按钮
        if (isVideoPlayerSite()) {
            console.log('检测到视频播放器页面，不创建悬浮按钮');
            return;
        }

        // 针对蓝奏云的特殊处理
        if (isLanzouSite()) {
            // 首先移除所有可能存在的悬浮按钮
            const allButtons = document.querySelectorAll('.bookmarks-float-btn');
            if (allButtons.length > 0) {
                console.log('蓝奏云特殊处理：移除所有现有按钮 (' + allButtons.length + '个)');
                for (let i = 0; i < allButtons.length; i++) {
                    try {
                        allButtons[i].remove();
                    } catch (e) {
                        console.error('移除按钮失败:', e);
                    }
                }
            }

            // 检查是否有其他框架或特殊元素
            const iframes = document.querySelectorAll('iframe');
            console.log('蓝奏云网站检测到' + iframes.length + '个iframe');

            // 蓝奏云上可能有特殊容器，这里添加特别检测并标记
            const lanzouSpecialContainers = document.querySelectorAll('#filecontent, #fileframe, .file-list');
            console.log('蓝奏云特殊容器数量: ' + lanzouSpecialContainers.length);
        }

        // 检查是否已存在DOM中的按钮 - 改进检测方式，针对iframe情况
        const existingButtons = document.querySelectorAll('.bookmarks-float-btn');
        if (existingButtons.length > 0) {
            console.log('已检测到DOM中存在' + existingButtons.length + '个悬浮按钮，清理多余按钮');
            // 保留第一个按钮，移除其它按钮
            for (let i = 1; i < existingButtons.length; i++) {
                try {
                    existingButtons[i].remove();
                    console.log('已移除多余的悬浮按钮');
                } catch (e) {
                    console.error('移除多余按钮失败:', e);
                }
            }

            // 返回第一个按钮
            if (existingButtons[0] && document.body.contains(existingButtons[0])) {
                return existingButtons[0];
            }
        }

        // 如果设置中禁用了悬浮按钮，则不创建
        if (!settings.floatButtonEnabled) {
            console.log('悬浮按钮已在设置中禁用');
            return;
        }

        // 特殊情况检测：检查当前页面是否在iframe中
        try {
            if (window.self !== window.top) {
                // 当前页面在iframe中，检查是否需要创建按钮
                // 对于像蓝奏云这样的网站，可能会在多个iframe中都创建按钮
                console.log('当前页面在iframe中，检查是否需要创建按钮');

                // 对于特定域名，如蓝奏云，可以选择不在iframe中创建按钮
                const currentDomain = window.location.hostname;
                if (currentDomain.includes('lanzou') || currentDomain.includes('lanzoui') ||
                    currentDomain.includes('lanzoux') || currentDomain.includes('woozooo.com')) {  // 增加woozooo.com域名判断
                    console.log('检测到蓝奏云网站，在iframe中不创建按钮');
                    return;
                }
            }
        } catch (e) {
            // 可能因为跨域问题无法检测iframe状态
            console.error('检测iframe状态失败:', e);
        }

        // 获取全局按钮状态
        const globalBtnStatus = GM_getValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
        const btnTimestamp = GM_getValue(FLOAT_BTN_TIMESTAMP_KEY, 0);
        const now = Date.now();

        // 如果全局状态显示按钮存在，且未过期，则不创建新按钮
        if (globalBtnStatus && (now - btnTimestamp < FLOAT_BTN_EXPIRE_TIME)) {
            console.log('全局悬浮按钮状态显示已存在且未过期，不再创建新按钮');
            return;
        }

        // 创建按钮
        const floatBtn = document.createElement('div');
        floatBtn.className = 'bookmarks-float-btn';
        floatBtn.id = 'bookmarks-float-btn-' + Date.now(); // 添加唯一ID
        floatBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
            <path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2zm0 15l-5-2.18L7 18V5h10v13z"/>
        </svg>`;
        floatBtn.title = '打开书签分组';

        // 添加点击事件
        floatBtn.addEventListener('click', function() {
            createBookmarksGroup();
        });

        console.log('创建新悬浮按钮:', floatBtn.id);

        // 添加到文档
        document.body.appendChild(floatBtn);

        // 更新全局按钮状态和时间戳
        GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, true);
        GM_setValue(FLOAT_BTN_TIMESTAMP_KEY, now);

        // 设置自动隐藏 - 启用悬浮按钮时始终自动隐藏
        setTimeout(() => {
            floatBtn.classList.add('hidden');
        }, settings.autoHideDelay);

        // 鼠标移入左侧边缘时显示
        document.addEventListener('mousemove', function(e) {
            if (e.clientX < 10) {
                floatBtn.classList.remove('hidden');
                // 鼠标离开时再次隐藏
                clearTimeout(floatBtn.hideTimeout);
                floatBtn.hideTimeout = setTimeout(() => {
                    if (!floatBtn.matches(':hover')) {
                        floatBtn.classList.add('hidden');
                    }
                }, settings.autoHideDelay);
            }
        });

        // 鼠标悬停时不隐藏
        floatBtn.addEventListener('mouseenter', function() {
            clearTimeout(floatBtn.hideTimeout);
        });

        // 鼠标离开后隐藏
        floatBtn.addEventListener('mouseleave', function() {
            floatBtn.hideTimeout = setTimeout(() => {
                floatBtn.classList.add('hidden');
            }, settings.autoHideDelay);
        });

        // 添加解除绑定事件
        window.addEventListener('beforeunload', function() {
            GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
        });

        // 定期检查按钮状态
        setInterval(function() {
            if (!document.body.contains(floatBtn)) {
                console.log('悬浮按钮已从DOM中移除，重置状态');
                GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
            } else {
                // 更新时间戳，表示按钮仍然活跃
                GM_setValue(FLOAT_BTN_TIMESTAMP_KEY, Date.now());
            }
        }, 30000); // 每30秒检查一次

        return floatBtn;
    }

    // 创建书签组面板
    function createBookmarksGroup() {
        // 检查是否已存在
        if (document.querySelector('.bookmarks-group-container')) {
            console.log('书签面板已存在，不重复创建');
            return;
        }

        // 面板打开时，移除可能存在的多余悬浮按钮
        cleanupExtraButtons();

        // 额外的清理：针对蓝奏云等特殊网站，检查并移除所有iframe内的按钮
        try {
            // 尝试找出所有iframe
            const iframes = document.querySelectorAll('iframe');
            console.log('检测到' + iframes.length + '个iframe，准备清理其中的按钮');

            // 遍历并尝试清理
            for (let i = 0; i < iframes.length; i++) {
                try {
                    const iframe = iframes[i];
                    if (iframe.contentDocument) {
                        const iframeButtons = iframe.contentDocument.querySelectorAll('.bookmarks-float-btn');
                        if (iframeButtons.length > 0) {
                            console.log('在iframe #' + i + '中发现' + iframeButtons.length + '个按钮，尝试清理');
                            for (let j = 0; j < iframeButtons.length; j++) {
                                try {
                                    iframeButtons[j].remove();
                                } catch (e) {
                                    console.error('移除iframe内按钮失败:', e);
                                }
                            }
                        }
                    }
                } catch (e) {
                    // 跨域iframe会拒绝访问
                    console.log('无法访问iframe #' + i + '内容（可能是跨域限制）');
                }
            }
        } catch (e) {
            console.error('清理iframe内按钮时出错:', e);
        }

        // 创建一个自动备份，确保数据安全
        try {
            const currentBookmarks = loadStoredBookmarks();
            if (Object.keys(currentBookmarks).length > 0) {
                const now = Date.now();
                const lastBackupTime = parseInt(GM_getValue(LAST_SAVE_TIME_KEY) || '0');
                const timeSinceLastBackup = now - lastBackupTime;

                // 如果超过7天没有备份，或者从未备份过，则创建备份
                if (timeSinceLastBackup > 7 * 24 * 60 * 60 * 1000 || lastBackupTime === 0) {
                    GM_setValue(BOOKMARKS_BACKUP_KEY, currentBookmarks);
                    GM_setValue(LAST_SAVE_TIME_KEY, now.toString());
                    console.log('已自动创建书签数据备份');
                }
            }
        } catch (error) {
            console.error('自动备份失败:', error);
        }

        // 创建容器覆盖层
        const container = document.createElement('div');
        container.className = 'bookmarks-group-container';

        // 创建主内容区
        const panel = document.createElement('div');
        panel.className = 'bookmarks-group';
        panel.style.position = 'absolute';
        panel.style.top = '50%';
        panel.style.left = '50%';
        panel.style.transform = 'translate(-50%, -50%)';

        // 创建头部
        const header = document.createElement('div');
        header.className = 'bookmarks-group-header';
        header.style.position = 'relative'; // 确保定位正确

        const title = document.createElement('h3');
        title.textContent = '浏览器书签分组';
        title.style.display = 'block'; // 确保标题显示
        title.style.visibility = 'visible'; // 确保标题可见

        const closeBtn = document.createElement('span');
        closeBtn.className = 'bookmarks-group-close';
        closeBtn.textContent = '×';
        closeBtn.title = '关闭';
        closeBtn.style.marginRight = '-10px'; // 收缩右侧

        header.appendChild(title);
        header.appendChild(closeBtn);

        // 创建工具栏
        const toolbar = document.createElement('div');
        toolbar.className = 'bookmarks-toolbar';

        // 导入按钮
        const importBtn = document.createElement('button');
        importBtn.className = 'bookmarks-toolbar-btn';
        importBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"/></svg> 点击导入`;
        toolbar.appendChild(importBtn);

        // 刷新按钮
        const refreshBtn = document.createElement('button');
        refreshBtn.className = 'bookmarks-toolbar-btn';
        refreshBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg> 刷新`;
        toolbar.appendChild(refreshBtn);

        // 新增全部导出按钮
        const exportAllBtn = document.createElement('button');
        exportAllBtn.className = 'bookmarks-toolbar-btn';
        exportAllBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg> 全部导出`;
        exportAllBtn.title = "将所有书签导出为JSON格式";
        toolbar.appendChild(exportAllBtn);

        // 全部导出按钮事件
        exportAllBtn.addEventListener('click', function() {
            // 获取所有书签
            const allBookmarks = loadStoredBookmarks();

            // 导出为JSON
            if (Object.keys(allBookmarks).length > 0) {
                exportBookmarksAsJson(allBookmarks);
            } else {
                alert('没有可导出的书签数据');
            }
        });

        // 新增重置按钮
        const resetBtn = document.createElement('button');
        resetBtn.className = 'bookmarks-toolbar-btn';
        resetBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 5V2L8 6l4 4V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg> 重置`;
        toolbar.appendChild(resetBtn);

        // 添加设置按钮
        const settingsBtn = document.createElement('button');
        settingsBtn.className = 'bookmarks-toolbar-btn';
        settingsBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22l-1.92 3.32c-.12.22-.07.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg> 设置`;
        toolbar.appendChild(settingsBtn);

        // 添加搜索容器
        const searchContainer = document.createElement('div');
        searchContainer.className = 'bookmarks-search-container';

        // 搜索图标
        const searchIcon = document.createElement('div');
        searchIcon.className = 'bookmarks-search-icon';
        searchIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>`;

        // 搜索输入框
        const searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.className = 'bookmarks-search-input';
        searchInput.placeholder = '搜索书签...';

        // 清除搜索按钮
        const searchClear = document.createElement('div');
        searchClear.className = 'bookmarks-search-close';
        searchClear.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>`;

        // 搜索结果容器
        const searchResults = document.createElement('div');
        searchResults.className = 'bookmarks-search-results';

        // 添加专门的滚轮事件处理，确保搜索结果容器可以正常滚动
        searchResults.addEventListener('wheel', function(e) {
            // 检查是否可以继续滚动
            const canScrollDown = this.scrollTop + this.clientHeight < this.scrollHeight;
            const canScrollUp = this.scrollTop > 0;

            // 只有在特定情况下阻止默认行为，允许正常滚动
            if ((e.deltaY > 0 && !canScrollDown) || (e.deltaY < 0 && !canScrollUp)) {
                e.preventDefault();
            }

            // 阻止冒泡到父元素
            e.stopPropagation();
        }, { passive: false, capture: true });

        // 组装搜索容器
        searchContainer.appendChild(searchIcon);
        searchContainer.appendChild(searchInput);
        searchContainer.appendChild(searchClear);
        searchContainer.appendChild(searchResults);

        // 将搜索容器添加到工具栏
        toolbar.appendChild(searchContainer);

        // 创建左侧面板（分组列表）
        const leftPanel = document.createElement('div');
        leftPanel.className = 'bookmarks-left-panel';

        // 创建右侧面板（书签内容）
        const rightPanel = document.createElement('div');
        rightPanel.className = 'bookmarks-right-panel';

        // 加载本地存储的书签
        const bookmarks = loadStoredBookmarks();
        if (Object.keys(bookmarks).length > 0) {
            renderBookmarkFolders(bookmarks, leftPanel, rightPanel);
        } else {
            // 尝试访问浏览器书签
            if (typeof chrome !== 'undefined' && chrome.bookmarks) {
                // Chrome 浏览器环境
                readChromeBookmarks(leftPanel, rightPanel);
            } else {
                // 不支持直接访问浏览器书签，显示导入选项
                showImportOptions(leftPanel, rightPanel);
            }
        }

        // 组装面板
        const contentWrapper = document.createElement('div');
        contentWrapper.style.display = 'flex';
        contentWrapper.style.flexDirection = 'column';
        contentWrapper.style.width = '100%';
        contentWrapper.style.height = '100%';
        contentWrapper.style.overflow = 'hidden'; // 防止内容溢出

        contentWrapper.appendChild(header);
        contentWrapper.appendChild(toolbar);

        const panelContent = document.createElement('div');
        panelContent.style.display = 'flex';
        panelContent.style.flexGrow = '1';
        panelContent.style.height = 'calc(100% - 130px)'; // 调整为130px以适应新的标题和工具栏间距
        panelContent.style.overflow = 'hidden';
        panelContent.style.boxSizing = 'border-box'; // 确保padding不增加宽度

        panelContent.appendChild(leftPanel);
        panelContent.appendChild(rightPanel);

        contentWrapper.appendChild(panelContent);
        panel.appendChild(contentWrapper);
        container.appendChild(panel);
        document.body.appendChild(container);

        // 添加关闭按钮事件
        closeBtn.addEventListener('click', function() {
            document.body.style.overflow = '';
            container.remove();
        });

        // 点击外部区域关闭面板
        container.addEventListener('click', function(e) {
            if (e.target === container) {
                document.body.style.overflow = '';
                container.remove();
            }
        });

        // 导入按钮事件
        importBtn.addEventListener('click', function() {
            showImportModal(container, leftPanel, rightPanel);
        });

        // 刷新按钮事件 - 修改为重载上次记住的书签地址
        refreshBtn.addEventListener('click', function() {
            // 获取最后使用的远程URL
            const remoteUrl = GM_getValue('lastRemoteUrl');

            if (remoteUrl) {
                // 如果有远程URL，重新加载远程书签
                loadRemoteBookmarks(remoteUrl, leftPanel, rightPanel);
            } else {
                // 没有远程URL，尝试重新渲染本地存储的书签
                const bookmarks = loadStoredBookmarks();
                if (Object.keys(bookmarks).length > 0) {
                    leftPanel.innerHTML = '';
                    rightPanel.innerHTML = '';
                    renderBookmarkFolders(bookmarks, leftPanel, rightPanel);
                    alert('书签已刷新！');
                } else {
                    alert('没有可刷新的书签数据，请先导入书签。');
                }
            }
        });

        // 重置按钮事件 - 实现原来的刷新功能
        resetBtn.addEventListener('click', function() {
            if (confirm('确定要重置书签数据吗？这将清空当前所有书签和设置。')) {
                // 清空所有相关数据
                GM_deleteValue(BOOKMARKS_KEY);
                GM_deleteValue('lastRemoteUrl');
                GM_deleteValue('lastSelectedFolder');
                GM_deleteValue('bookmarkPositions');
                GM_deleteValue(SETTINGS_KEY);

                // 不删除备份，保留以便需要时恢复

                // 重置设置为默认值
                settings = {...defaultSettings};

                // 移除悬浮按钮
                const floatBtn = document.querySelector('.bookmarks-float-btn');
                if (floatBtn) {
                    floatBtn.remove();
                }

                // 如果设置允许,重新创建悬浮按钮
                if (settings.floatButtonEnabled) {
                    createFloatButton();
                }

                // 显示导入选项
                showImportOptions(leftPanel, rightPanel);

                alert('所有数据已重置！');
            }
        });

        // 设置按钮事件
        settingsBtn.addEventListener('click', function() {
            showSettingsModal(container);
        });

        // 搜索功能 - 监听输入事件
        searchInput.addEventListener('input', function() {
            const query = this.value.trim();

            // 显示或隐藏清除按钮
            searchClear.style.display = query ? 'flex' : 'none';

            if (query) {
                // 执行搜索并显示结果
                performSearch(query, searchResults, bookmarks, leftPanel, rightPanel);
                searchResults.style.display = 'block';

                // 修复搜索结果滚动
                setTimeout(fixSearchResultsScrolling, 50);
            } else {
                // 清空并隐藏搜索结果
                searchResults.innerHTML = '';
                searchResults.style.display = 'none';
            }
        });

        // 搜索框聚焦事件 - 如果有搜索内容，显示搜索结果
        searchInput.addEventListener('focus', function() {
            const query = this.value.trim();
            if (query) {
                performSearch(query, searchResults, bookmarks, leftPanel, rightPanel);
                searchResults.style.display = 'block';
                searchClear.style.display = 'flex';

                // 修复搜索结果滚动
                setTimeout(fixSearchResultsScrolling, 50);
            }
        });

        // 点击清除按钮事件
        searchClear.addEventListener('click', function() {
            searchInput.value = '';
            searchResults.innerHTML = '';
            searchResults.style.display = 'none';
            this.style.display = 'none';
            searchInput.focus();
        });

        // 点击页面其他地方隐藏搜索结果
        document.addEventListener('click', function(e) {
            if (!searchContainer.contains(e.target)) {
                searchResults.style.display = 'none';
            }
        });

        // 阻止搜索结果内的点击事件冒泡
        searchResults.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 使面板可拖动
        makeDraggable(panel, header);

        // 阻止滚轮事件冒泡，防止背景页面滚动
        container.addEventListener('wheel', function(e) {
            e.stopPropagation();
            e.preventDefault();
        }, { passive: false });

        // 为左侧面板添加滚动事件处理
        leftPanel.addEventListener('wheel', function(e) {
            e.stopPropagation();
        }, { passive: false });

        // 为右侧面板添加滚动事件处理
        rightPanel.addEventListener('wheel', function(e) {
            e.stopPropagation();
        }, { passive: false });

        // 添加全局事件监听，确保面板打开时背景不滚动
        document.body.style.overflow = 'hidden';

        // 应用滚动修复
        setTimeout(fixScrollingIssues, 100);

        // 多次应用滚动修复，确保在DOM渲染完成后生效
        setTimeout(fixScrollingIssues, 500);
        setTimeout(fixScrollingIssues, 1000);

        // 特别处理内容容器的滚动问题
        setTimeout(() => {
            const contentContainer = document.getElementById('bookmarks-container-content');
            if (contentContainer) {
                // 移除可能存在的事件监听器，防止重复
                if (contentContainer._scrollHandler) {
                    contentContainer.removeEventListener('wheel', contentContainer._scrollHandler);
                }

                // 只阻止冒泡，允许默认滚动行为
                contentContainer._scrollHandler = function(e) {
                    // 仅阻止事件冒泡，避免背景页面滚动
                    e.stopPropagation();

                    // 允许默认滚动行为正常进行
                    // 不进行任何干预或阻止
                };

                // 添加事件监听器，不使用passive: false以允许默认滚动
                contentContainer.addEventListener('wheel', contentContainer._scrollHandler, { capture: true });

                console.log('为内容容器添加了简化的滚动处理');
            }
        }, 1000);

        // 特别针对搜索结果容器的滚动修复
        fixSearchResultsScrolling();

        // 处理搜索结果滚动
        handleSearchResultsScrolling();
    }

    // 从存储中加载书签
    function loadStoredBookmarks() {
        try {
            // 仅从GM_getValue中获取，确保数据全局同步
            let bookmarks = GM_getValue(BOOKMARKS_KEY);
            if (bookmarks && isValidBookmarks(bookmarks)) {
                console.log('从GM全局存储加载书签成功');
                return bookmarks;
            }

            // 尝试从备份恢复
            let backupBookmarks = GM_getValue(BOOKMARKS_BACKUP_KEY);
            if (backupBookmarks && isValidBookmarks(backupBookmarks)) {
                console.log('从GM全局备份恢复书签成功');
                GM_setValue(BOOKMARKS_KEY, backupBookmarks);
                return backupBookmarks;
            }

            // 尝试从localStorage迁移数据(向后兼容，仅一次性)
            try {
                const localBookmarksStr = localStorage.getItem(BOOKMARKS_KEY);
                if (localBookmarksStr) {
                    const localBookmarks = JSON.parse(localBookmarksStr);
                    if (isValidBookmarks(localBookmarks)) {
                        console.log('从localStorage迁移书签数据到GM全局存储');
                        GM_setValue(BOOKMARKS_KEY, localBookmarks);

                        // 备份数据
                        GM_setValue(BOOKMARKS_BACKUP_KEY, localBookmarks);
                        return localBookmarks;
                    }
                }

                // 最后尝试从localStorage备份恢复
                const backupStr = localStorage.getItem(BOOKMARKS_BACKUP_KEY);
                if (backupStr) {
                    const backupData = JSON.parse(backupStr);
                    if (isValidBookmarks(backupData)) {
                        console.log('从localStorage备份迁移数据到GM全局存储');
                        GM_setValue(BOOKMARKS_KEY, backupData);
                        GM_setValue(BOOKMARKS_BACKUP_KEY, backupData);
                        return backupData;
                    }
                }
            } catch (error) {
                console.error('迁移本地数据失败:', error);
            }

            // 如果没有有效数据，返回空对象
            console.log('没有找到有效的书签数据，返回空对象');
            return {};
        } catch (error) {
            console.error('加载存储的书签失败:', error);
            return {};
        }
    }

    // 验证书签数据是否有效
    function isValidBookmarks(bookmarks) {
        // 检查是否是对象
        if (!bookmarks || typeof bookmarks !== 'object' || Array.isArray(bookmarks)) {
            return false;
        }

        // 检查是否有至少一个文件夹
        const folderNames = Object.keys(bookmarks);
        if (folderNames.length === 0) {
            return false;
        }

        // 检查每个文件夹是否有效
        for (const folder of folderNames) {
            const items = bookmarks[folder];
            // 检查是否是数组
            if (!Array.isArray(items)) {
                return false;
            }

            // 不强制要求每个文件夹都有书签，允许空文件夹
        }

        return true;
    }

    // 保存书签到存储
    function saveBookmarks(bookmarks) {
        try {
            // 验证数据有效性
            if (!isValidBookmarks(bookmarks)) {
                console.error('尝试保存无效的书签数据');
                return false;
            }

            // 保存到GM_setValue全局存储
            GM_setValue(BOOKMARKS_KEY, bookmarks);
            console.log('书签数据已保存到GM全局存储');

            // 备份逻辑
            const now = Date.now();
            const lastBackupTime = parseInt(GM_getValue(LAST_SAVE_TIME_KEY, '0'));

            // 检查是否需要备份
            if (settings.enableBackup !== false) {
                const backupInterval = settings.backupInterval || BACKUP_INTERVAL;

                if (now - lastBackupTime >= backupInterval) {
                    // 创建备份
                    GM_setValue(BOOKMARKS_BACKUP_KEY, bookmarks);
                    GM_setValue(LAST_SAVE_TIME_KEY, now.toString());
                    console.log('已创建书签数据备份到GM全局存储');
                }
            }

            return true;
        } catch (error) {
            console.error('保存书签失败:', error);
            return false;
        }
    }

    // 保存书签位置状态
    function saveBookmarkPosition(folderName, scrollPosition) {
        try {
            const positionKey = 'bookmarkPositions';
            let positions = GM_getValue(positionKey, {});

            // 如果返回的是字符串（兼容旧版本），则解析
            if (typeof positions === 'string') {
                positions = JSON.parse(positions);
            }

            positions[folderName] = scrollPosition;
            GM_setValue(positionKey, positions);
        } catch (error) {
            console.error('保存书签位置失败:', error);
        }
    }

    // 加载书签位置状态
    function loadBookmarkPosition(folderName) {
        try {
            const positionKey = 'bookmarkPositions';
            let positions = GM_getValue(positionKey, {});

            // 如果返回的是字符串（兼容旧版本），则解析
            if (typeof positions === 'string') {
                positions = JSON.parse(positions);
            }

            return positions[folderName] || 0;
        } catch (error) {
            console.error('加载书签位置失败:', error);
            return 0;
        }
    }

    // 尝试读取Chrome浏览器书签
    function readChromeBookmarks(leftPanel, rightPanel) {
        try {
            chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
                // 处理书签树
                const bookmarkFolders = {};

                // 递归处理书签节点
                function processBookmarkNodes(nodes, parentFolder) {
                    for (let node of nodes) {
                        if (node.children) {
                            // 这是一个文件夹
                            const folderName = node.title || "未命名文件夹";
                            if (!bookmarkFolders[folderName]) {
                                bookmarkFolders[folderName] = [];
                            }

                            // 递归处理子节点
                            processBookmarkNodes(node.children, folderName);
                        } else if (parentFolder && node.url) {
                            // 这是一个书签
                            try {
                                // 提取域名以获取图标
                                const urlObj = new URL(node.url);
                                const favicon = `https://favicon.yandex.net/favicon/${urlObj.hostname}`;

                                bookmarkFolders[parentFolder].push({
                                    title: node.title || "未命名书签",
                                    url: node.url,
                                    favicon: favicon
                                });
                            } catch (e) {
                                // URL解析失败，使用默认图标
                                bookmarkFolders[parentFolder].push({
                                    title: node.title || "未命名书签",
                                    url: node.url,
                                    favicon: ''
                                });
                            }
                        }
                    }
                }

                // 处理根书签文件夹
                processBookmarkNodes(bookmarkTreeNodes, null);

                // 保存书签到本地存储
                saveBookmarks(bookmarkFolders);

                // 显示文件夹和书签
                renderBookmarkFolders(bookmarkFolders, leftPanel, rightPanel);
            });
        } catch (error) {
            console.error("无法访问浏览器书签:", error);
            showImportOptions(leftPanel, rightPanel);
        }
    }

    // 渲染书签文件夹和内容
    function renderBookmarkFolders(bookmarks, leftPanel, rightPanel) {
        // 清空左侧面板
        leftPanel.innerHTML = '';

        // 创建分类列表（左侧）
        const categoryList = document.createElement('div');
        categoryList.className = 'bookmarks-category-list';

        // 获取有效文件夹列表
        const folderNames = Object.keys(bookmarks).filter(folderName =>
            bookmarks[folderName] && bookmarks[folderName].length > 0);

        // 记住上次选择的分组
        let lastSelectedFolder = GM_getValue('lastSelectedFolder');
        if (!lastSelectedFolder || !folderNames.includes(lastSelectedFolder)) {
            lastSelectedFolder = folderNames[0] || '';
        }

        // 为每个分类创建项目
        folderNames.forEach((folderName, index) => {
            const categoryItem = document.createElement('div');
            categoryItem.className = 'bookmarks-category-item';

            // 添加文件夹图标
            const folderIcon = document.createElement('span');
            folderIcon.className = 'folder-icon';
            folderIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M20 5h-8.586L9.707 3.293A.997.997 0 0 0 9 3H4c-1.103 0-2 .897-2 2v14c0 1.103.897 2 2 2h16c1.103 0 2-.897 2-2V7c0-1.103-.897-2-2-2zM4 19V7h16l.002 12H4z"/></svg>';
            categoryItem.appendChild(folderIcon);

            // 添加文本容器
            const textContainer = document.createElement('span');
            textContainer.className = 'folder-text';
            textContainer.textContent = folderName;
            categoryItem.appendChild(textContainer);

            // 添加计数
            const countContainer = document.createElement('span');
            countContainer.className = 'folder-count';
            countContainer.textContent = `(${bookmarks[folderName].length})`;
            categoryItem.appendChild(countContainer);

            // 默认选中上次选择的分类或第一个分类
            if (folderName === lastSelectedFolder) {
                categoryItem.classList.add('active');
            }

            categoryList.appendChild(categoryItem);

            // 添加点击事件
            categoryItem.addEventListener('click', function() {
                // 移除所有活跃状态
                document.querySelectorAll('.bookmarks-category-item').forEach(item => {
                    item.classList.remove('active');
                });

                // 设置当前项目为活跃
                this.classList.add('active');

                // 记住选择的分组
                GM_setValue('lastSelectedFolder', folderName);

                // 显示对应分类的内容
                showFolderContent(folderName, bookmarks[folderName], rightPanel);
            });
        });

        leftPanel.appendChild(categoryList);

        // 默认显示上次选择的分组或第一个分组的内容
        if (folderNames.length > 0) {
            showFolderContent(lastSelectedFolder, bookmarks[lastSelectedFolder], rightPanel);
        }

        // 应用滚动修复
        setTimeout(fixScrollingIssues, 100);
    }

    // 显示文件夹内容
    function showFolderContent(folderName, bookmarkList, rightPanel) {
        // 清空右侧面板
        rightPanel.innerHTML = '';

        // 添加分组标题
        const groupTitle = document.createElement('div');
        groupTitle.className = 'bookmarks-group-title';

        const titleText = document.createElement('span');
        titleText.textContent = folderName;
        groupTitle.appendChild(titleText);

        // 添加导出JSON按钮
        const exportBtn = document.createElement('button');
        exportBtn.className = 'bookmarks-export-btn';
        exportBtn.textContent = '导出为JSON';
        exportBtn.title = '将当前分组导出为JSON格式';
        exportBtn.addEventListener('click', function() {
            // 创建包含当前分组的书签对象
            const exportData = {};
            exportData[folderName] = bookmarkList;

            // 导出为JSON
            exportBookmarksAsJson(exportData);
        });

        groupTitle.appendChild(exportBtn);

        rightPanel.appendChild(groupTitle);

        // 创建书签容器，用于滚动
        const bookmarksContainer = document.createElement('div');
        bookmarksContainer.id = 'bookmarks-container-content';

        // 确保容器有正确的样式
        bookmarksContainer.style.overflowY = 'auto';
        bookmarksContainer.style.flexGrow = '1';
        bookmarksContainer.style.overflowX = 'hidden';
        bookmarksContainer.style.height = 'calc(100% - 35px)';
        bookmarksContainer.style.scrollBehavior = 'auto';

        // 移除可能存在的事件监听器，防止重复
        if (bookmarksContainer._scrollHandler) {
            bookmarksContainer.removeEventListener('wheel', bookmarksContainer._scrollHandler);
        }

        // 只阻止冒泡，允许默认滚动行为
        bookmarksContainer._scrollHandler = function(e) {
            // 仅阻止事件冒泡，避免背景页面滚动
            e.stopPropagation();
            // 不干预默认滚动
        };

        // 使用capture确保优先处理，但不使用passive: false以允许默认滚动
        bookmarksContainer.addEventListener('wheel', bookmarksContainer._scrollHandler, { capture: true });

        // 添加书签列表
        if (bookmarkList && bookmarkList.length) {
            bookmarkList.forEach(bookmark => {
                const itemElement = document.createElement('div');
                itemElement.className = 'bookmarks-item';

                const linkElement = document.createElement('a');
                linkElement.href = bookmark.url;
                linkElement.textContent = bookmark.title;
                linkElement.title = bookmark.title;

                // 创建图标元素
                const iconElement = createFaviconElement(bookmark.url);

                // 插入图标到链接前
                linkElement.prepend(iconElement);

                // 处理不同类型的书签
                if (bookmark.url && bookmark.url.startsWith('javascript:')) {
                    handleJavaScriptBookmark(linkElement, bookmark);
                } else {
                    linkElement.target = '_blank';
                    linkElement.rel = 'noopener noreferrer';
                }

                itemElement.appendChild(linkElement);
                bookmarksContainer.appendChild(itemElement);
            });
        } else {
            const emptyMessage = document.createElement('div');
            emptyMessage.style.textAlign = 'center';
            emptyMessage.style.padding = '20px';
            emptyMessage.style.color = '#666';
            emptyMessage.textContent = '该分组没有书签';
            bookmarksContainer.appendChild(emptyMessage);
        }

        rightPanel.appendChild(bookmarksContainer);

        // 设置滚动位置
        const savedPosition = loadBookmarkPosition(folderName);
        setTimeout(() => {
            bookmarksContainer.scrollTop = savedPosition;
        }, 0);

        // 记录滚动位置
        bookmarksContainer.addEventListener('scroll', function() {
            saveBookmarkPosition(folderName, this.scrollTop);
        });
    }

    // 处理JavaScript书签
    function handleJavaScriptBookmark(linkElement, bookmark) {
        linkElement.addEventListener('click', function(e) {
            e.preventDefault();

            // 关闭面板
            const container = document.querySelector('.bookmarks-group-container');
            if (container) {
                container.remove();
            }

            // 延迟执行书签代码，确保面板已关闭
            setTimeout(function() {
                try {
                    // 移除javascript:前缀
                    const code = bookmark.url.substring(11);
                    // 执行代码
                    new Function(decodeURIComponent(code))();
                } catch (error) {
                    console.error('执行书签代码时出错:', error);
                }
            }, 100);
        });
    }

    // 显示导入模态框
    function showImportModal(container, leftPanel, rightPanel) {
        // 创建导入模态框
        const modal = document.createElement('div');
        modal.className = 'bookmarks-import-modal';
        modal.style.maxWidth = '500px';
        modal.style.width = '90%';

        // 模态框内容
        modal.innerHTML = `
            <h3>导入书签</h3>
            <div class="bookmarks-tab-options">
                <div class="bookmarks-tab-option active" data-tab="local">本地导入</div>
                <div class="bookmarks-tab-option" data-tab="remote">远程导入</div>
            </div>

            <!-- 本地导入选项 -->
            <div id="local-tab-content" class="bookmarks-tab-content active">
                <p style="margin-bottom: 20px; color: #666; font-size: 14px;">从本地文件导入书签：</p>
                <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 15px;">
                    <button id="import-html-btn" class="bookmarks-import-btn" style="flex: 1; background-color: #1a73e8; color: white; border: none; border-radius: 4px; padding: 10px; font-size: 14px; cursor: pointer;">导入HTML书签</button>
                    <button id="import-json-btn" class="bookmarks-import-btn" style="flex: 1; background-color: #1a73e8; color: white; border: none; border-radius: 4px; padding: 10px; font-size: 14px; cursor: pointer;">导入JSON书签</button>
                </div>
                <button id="import-bookmarks-btn" class="bookmarks-import-btn" style="width: 100%; background-color: #1a73e8; color: white; border: none; border-radius: 4px; padding: 10px; font-size: 14px; cursor: pointer; margin-bottom: 15px;">导入Bookmarks文件</button>
            </div>

            <!-- 远程导入选项 -->
            <div id="remote-tab-content" class="bookmarks-tab-content">
                <p style="margin-bottom: 15px; color: #666; font-size: 14px;">从远程URL导入书签：</p>
                <input type="text" id="remote-url-input" class="bookmarks-import-url" placeholder="https://example.com/bookmarks.json" style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                <button id="load-remote-btn" class="bookmarks-import-btn" style="width: 100%; background-color: #1a73e8; color: white; border: none; border-radius: 4px; padding: 10px; font-size: 14px; cursor: pointer;">加载远程书签</button>
            </div>

            <div class="bookmarks-import-btns" style="display: flex; justify-content: flex-end; margin-top: 20px; gap: 10px;">
                <button class="bookmarks-import-btn bookmarks-import-cancel" style="background-color: #f5f5f5; border: 1px solid #ddd; color: #333; border-radius: 4px; padding: 8px 12px; cursor: pointer;">取消</button>
            </div>
        `;

        container.appendChild(modal);

        // 阻止事件冒泡
        modal.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 添加标签切换功能
        const tabOptions = modal.querySelectorAll('.bookmarks-tab-option');
        const tabContents = modal.querySelectorAll('.bookmarks-tab-content');

        tabOptions.forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有激活状态
                tabOptions.forEach(t => t.classList.remove('active'));
                tabContents.forEach(c => c.classList.remove('active'));

                // 激活当前标签
                this.classList.add('active');
                const tabName = this.getAttribute('data-tab');
                document.getElementById(`${tabName}-tab-content`).classList.add('active');
            });
        });

        // 获取按钮元素
        const importHtmlBtn = modal.querySelector('#import-html-btn');
        const importJsonBtn = modal.querySelector('#import-json-btn');
        const importBookmarksBtn = modal.querySelector('#import-bookmarks-btn');
        const loadRemoteBtn = modal.querySelector('#load-remote-btn');
        const cancelBtn = modal.querySelector('.bookmarks-import-cancel');

        // 取消按钮事件
        cancelBtn.addEventListener('click', function() {
            modal.remove();
        });

        // 添加按钮悬停效果
        const allButtons = modal.querySelectorAll('.bookmarks-import-btn');
        allButtons.forEach(button => {
            if (button !== cancelBtn) {
                button.addEventListener('mouseenter', function() {
                    this.style.backgroundColor = '#1557b0';
                });

                button.addEventListener('mouseleave', function() {
                    this.style.backgroundColor = '#1a73e8';
                });
            }
        });

        // 导入HTML书签
        importHtmlBtn.addEventListener('click', function() {
            directImportFile('.html,.htm', leftPanel, rightPanel, 'html');
            modal.remove();
        });

        // 导入JSON书签
        importJsonBtn.addEventListener('click', function() {
            directImportFile('.json', leftPanel, rightPanel, 'json');
            modal.remove();
        });

        // 导入Bookmarks文件
        importBookmarksBtn.addEventListener('click', function() {
            directImportFile('', leftPanel, rightPanel, 'bookmarks');
            modal.remove();
        });

        // 加载远程书签
        loadRemoteBtn.addEventListener('click', function() {
            const remoteUrl = modal.querySelector('#remote-url-input').value.trim();

            if (remoteUrl) {
                // 加载远程书签
                loadRemoteBookmarks(remoteUrl, leftPanel, rightPanel);
                modal.remove();
            } else {
                alert('请输入有效的远程URL');
            }
        });
    }

    // 刷新书签
    function refreshBookmarks(leftPanel, rightPanel) {
        // 获取当前选中的分组
        const currentFolder = GM_getValue('lastSelectedFolder');

        // 检查是否有远程URL
        const remoteUrl = GM_getValue('lastRemoteUrl');

        if (remoteUrl) {
            // 如果有远程URL，重新加载远程书签
            loadRemoteBookmarks(remoteUrl, leftPanel, rightPanel);
        } else {
            // 否则尝试重新加载本地存储的书签
            const bookmarks = loadStoredBookmarks();
            if (Object.keys(bookmarks).length > 0) {
                // 清空面板
                leftPanel.innerHTML = '';
                rightPanel.innerHTML = '';

                // 重新渲染书签
                renderBookmarkFolders(bookmarks, leftPanel, rightPanel);
                alert('书签已刷新！');
            } else {
                // 如果没有书签数据，提示用户导入
                if (confirm('没有找到书签数据，是否导入书签？')) {
                    showImportOptions(leftPanel, rightPanel);
                }
            }
        }
    }

    // 从远程加载书签
    function loadRemoteBookmarks(url, leftPanel, rightPanel) {
        // 保存远程URL以便刷新
        GM_setValue('lastRemoteUrl', url);

        // 显示加载中提示
        leftPanel.innerHTML = '<div style="padding: 20px; text-align: center;">加载中...</div>';
        rightPanel.innerHTML = '';

        // 加载远程书签
        GM_xmlhttpRequest({
            method: 'GET',
            url: url,
            onload: function(response) {
                try {
                    // 先尝试解析为JSON
                    try {
                        const remoteData = JSON.parse(response.responseText);
                        // JSON解析成功，按JSON格式处理
                        saveBookmarks(remoteData);
                        leftPanel.innerHTML = '';
                        rightPanel.innerHTML = '';
                        renderBookmarkFolders(remoteData, leftPanel, rightPanel);
                        alert('远程书签加载成功！');
                        return;
                    } catch (jsonError) {
                        console.log('远程文件不是JSON格式，尝试作为Bookmarks或HTML解析');
                    }

                    // 如果不是JSON，尝试作为Bookmarks文件解析
                    try {
                        // 尝试检测是否包含Chrome/Edge Bookmarks文件特征
                        if(response.responseText.includes('"roots"') &&
                           (response.responseText.includes('"bookmark_bar"') ||
                            response.responseText.includes('"other"'))) {
                            // 看起来是Bookmarks文件
                            parseBookmarksFile(response.responseText, leftPanel, rightPanel);
                            alert('远程Bookmarks文件加载成功！');
                            return;
                        }
                    } catch (bookmarkError) {
                        console.log('不是Bookmarks格式，尝试作为HTML解析');
                    }

                    // 最后尝试作为HTML书签文件解析
                    try {
                        // 检查是否包含HTML书签文件的特征
                        if(response.responseText.includes('<DL>') ||
                           response.responseText.includes('<dl>') ||
                           response.responseText.includes('BOOKMARK') ||
                           response.responseText.includes('bookmark')) {
                            // 看起来是HTML书签文件
                            parseBookmarkHTML(response.responseText, leftPanel, rightPanel);
                            alert('远程HTML书签文件加载成功！');
                            return;
                        }
                    } catch (htmlError) {
                        console.error('HTML解析失败:', htmlError);
                    }

                    // 如果所有解析方法都失败
                    throw new Error('无法识别的书签文件格式');

                } catch (error) {
                    console.error('解析远程书签失败:', error);
                    alert('远程书签加载失败，请检查URL和数据格式: ' + error.message);

                    // 如果加载失败且本地没有书签数据，显示导入选项
                    const bookmarks = loadStoredBookmarks();
                    if (Object.keys(bookmarks).length === 0) {
                        showImportOptions(leftPanel, rightPanel);
                    }
                }
            },
            onerror: function(error) {
                console.error('远程书签请求失败:', error);
                alert('远程书签请求失败，请检查网络连接和URL');

                // 如果请求失败且本地没有书签数据，显示导入选项
                const bookmarks = loadStoredBookmarks();
                if (Object.keys(bookmarks).length === 0) {
                    showImportOptions(leftPanel, rightPanel);
                }
            }
        });
    }

    // 显示导入选项
    function showImportOptions(leftPanel, rightPanel) {
        // 清空面板
        leftPanel.innerHTML = '';
        rightPanel.innerHTML = '';

        // 保留左侧面板，调整样式用于显示Bookmarks文件位置信息
        leftPanel.style.display = 'block';  // 确保显示
        leftPanel.style.width = '260px';    // 设置合适宽度
        leftPanel.style.padding = '20px';   // 添加内边距
        leftPanel.style.backgroundColor = '#f9f9f9';  // 浅灰色背景
        leftPanel.style.borderRight = '1px solid #eee';  // 右侧边框
        leftPanel.style.boxSizing = 'border-box';  // 确保内边距不增加宽度

        // 添加Bookmarks文件位置信息到左侧面板 - 移除红色竖线
        leftPanel.innerHTML = `
            <div style="margin-bottom: 20px;">
                <div style="font-weight: 600; font-size: 16px; color: #333; margin-bottom: 12px;">Bookmarks文件位置:</div>

                <div style="margin-bottom: 15px;">
                    <div style="font-weight: 600; margin-bottom: 5px;">User Data\\Default 路径:</div>
                </div>

                <div style="margin-bottom: 15px;">
                    <div style="font-weight: 600; margin-bottom: 5px;">Microsoft Edge:</div>
                    <div style="font-size: 13px; word-break: break-all; color: #555;">%LocalAppData%\\Microsoft\\Edge\\<span style="color: #e53935; font-weight: 600;">User Data\\Default</span></div>
                </div>

                <div style="margin-bottom: 15px;">
                    <div style="font-weight: 600; margin-bottom: 5px;">Google Chrome:</div>
                    <div style="font-size: 13px; word-break: break-all; color: #555;">%LocalAppData%\\Google\\Chrome\\<span style="color: #e53935; font-weight: 600;">User Data\\Default</span></div>
                </div>

                <div style="margin-bottom: 15px;">
                    <div style="font-weight: 600; margin-bottom: 5px;">360浏览器:</div>
                    <div style="font-size: 13px; word-break: break-all; color: #555;">安装目录\\<span style="color: #e53935; font-weight: 600;">User Data\\Default</span></div>
                </div>

                <div style="margin-bottom: 15px;">
                    <div style="font-weight: 600; margin-bottom: 5px;">QQ浏览器:</div>
                    <div style="font-size: 13px; word-break: break-all; color: #555;">%LocalAppData%\\Tencent\\QQBrowser\\<span style="color: #e53935; font-weight: 600;">User Data\\Default</span></div>
                </div>
            </div>
        `;

        // 设置右侧面板样式
        rightPanel.style.padding = '20px';
        rightPanel.style.boxSizing = 'border-box';
        rightPanel.style.overflowY = 'auto';

        // 添加导入选项到右侧面板
        const importOptionsContainer = document.createElement('div');
        importOptionsContainer.style.backgroundColor = 'white';
        importOptionsContainer.style.padding = '30px';
        importOptionsContainer.style.borderRadius = '8px';
        importOptionsContainer.style.boxShadow = '0 2px 10px rgba(0,0,0,0.08)';
        importOptionsContainer.style.border = '1px solid #e0e0e0';

        importOptionsContainer.innerHTML = `
            <h4 style="font-size: 24px; color: #1a73e8; margin-bottom: 30px; font-weight: 600;">请选择导入方式:</h4>

            <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 20px;">
                <button id="import-html-btn" style="flex: 1; min-width: 200px; white-space: nowrap; padding: 12px 20px; background-color: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500; box-shadow: 0 1px 3px rgba(0,0,0,0.12); transition: all 0.2s ease;">导入HTML书签</button>

                <button id="import-bookmarks-btn" style="flex: 1; min-width: 200px; white-space: nowrap; padding: 12px 20px; background-color: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500; box-shadow: 0 1px 3px rgba(0,0,0,0.12); transition: all 0.2s ease;">导入Bookmarks文件</button>
            </div>

            <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 20px;">
                <button id="convert-html-btn" style="flex: 1; min-width: 200px; white-space: nowrap; padding: 12px 20px; background-color: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500; box-shadow: 0 1px 3px rgba(0,0,0,0.12); transition: all 0.2s ease;">HTML转JSON</button>

                <button id="convert-bookmarks-btn" style="flex: 1; min-width: 200px; white-space: nowrap; padding: 12px 20px; background-color: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500; box-shadow: 0 1px 3px rgba(0,0,0,0.12); transition: all 0.2s ease;">Bookmarks转JSON</button>
            </div>

            <p style="margin-top: 30px; font-size: 14px; color: #666;">提示：使用转换功能将书签文件转为JSON格式，可以上传到不审核JSON文件的平台使用</p>
        `;

        rightPanel.appendChild(importOptionsContainer);

        // 获取按钮元素
        const importHtmlBtn = rightPanel.querySelector('#import-html-btn');
        const importBookmarksBtn = rightPanel.querySelector('#import-bookmarks-btn');
        const convertHtmlBtn = rightPanel.querySelector('#convert-html-btn');
        const convertBookmarksBtn = rightPanel.querySelector('#convert-bookmarks-btn');

        // 添加按钮悬停效果
        const allButtons = rightPanel.querySelectorAll('button');
        allButtons.forEach(button => {
            button.addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#0d5bdd';
                this.style.boxShadow = '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)';
            });

            button.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '#1a73e8';
                this.style.boxShadow = '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)';
            });
        });

        // 添加HTML书签导入按钮事件 - 直接调用文件选择器
        importHtmlBtn.addEventListener('click', function() {
            // 直接打开HTML文件选择器
            directImportFile('.html,.htm', leftPanel, rightPanel, 'html');
        });

        // 添加Bookmarks文件导入按钮事件 - 直接调用文件选择器
        importBookmarksBtn.addEventListener('click', function() {
            // 直接打开Bookmarks文件选择器
            directImportFile('', leftPanel, rightPanel, 'bookmarks');
        });

        // HTML转JSON按钮事件
        convertHtmlBtn.addEventListener('click', function() {
            importFile('.html,.htm', (content) => {
                // 创建临时面板用于解析
                const tempLeftPanel = document.createElement('div');
                const tempRightPanel = document.createElement('div');

                // 解析HTML并导出为JSON
                try {
                    // 先解析HTML书签
                    const tempBookmarks = {};
                    const tempParser = new DOMParser();
                    const tempDoc = tempParser.parseFromString(content, 'text/html');

                    // 处理默认文件夹
                    tempBookmarks['导入的书签'] = [];
                    tempBookmarks['未分组书签'] = [];

                    // 使用现有的解析函数解析数据
                    parseBookmarkHTML(content, tempLeftPanel, tempRightPanel);

                    // 获取解析后的数据
                    const bookmarks = loadStoredBookmarks();

                    // 导出为JSON
                    if (exportBookmarksAsJson(bookmarks)) {
                        alert('HTML书签已成功转换为JSON格式并下载！现在您可以将此JSON文件上传到您的文件托管平台。');
                    }
                } catch (error) {
                    console.error('转换书签失败:', error);
                    alert('转换书签失败: ' + error.message);
                }
            });
        });

        // Bookmarks转JSON按钮事件
        convertBookmarksBtn.addEventListener('click', function() {
            importFile('', (content) => {
                // 创建临时面板用于解析
                const tempLeftPanel = document.createElement('div');
                const tempRightPanel = document.createElement('div');

                // 解析Bookmarks并导出为JSON
                try {
                    // 使用现有的解析函数解析数据
                    parseBookmarksFile(content, tempLeftPanel, tempRightPanel);

                    // 获取解析后的数据
                    const bookmarks = loadStoredBookmarks();

                    // 导出为JSON
                    if (exportBookmarksAsJson(bookmarks)) {
                        alert('Bookmarks文件已成功转换为JSON格式并下载！现在您可以将此JSON文件上传到您的文件托管平台。');
                    }
                } catch (error) {
                    console.error('转换书签失败:', error);
                    alert('转换书签失败: ' + error.message);
                }
            });
        });
    }

    // 添加直接导入文件的辅助函数
    function directImportFile(accept, leftPanel, rightPanel, fileType) {
        // 创建一个隐藏的文件输入元素
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = accept;
        fileInput.style.display = 'none';
        document.body.appendChild(fileInput);

        // 监听文件选择事件
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];
                const reader = new FileReader();

                reader.onload = function(e) {
                    const content = e.target.result;

                    try {
                        // 清理面板样式
                        leftPanel.innerHTML = '';
                        leftPanel.style = ''; // 移除所有内联样式
                        rightPanel.innerHTML = '';
                        rightPanel.style = ''; // 移除所有内联样式

                        // 根据文件类型处理
                        if (fileType === 'html') {
                            parseBookmarkHTML(content, leftPanel, rightPanel);
                        } else if (fileType === 'bookmarks') {
                            parseBookmarksFile(content, leftPanel, rightPanel);
                        } else if (fileType === 'json') {
                            try {
                                const jsonData = JSON.parse(content);
                                saveBookmarks(jsonData);
                                renderBookmarkFolders(jsonData, leftPanel, rightPanel);
                                alert('JSON书签导入成功！');
                            } catch (err) {
                                console.error('JSON解析失败:', err);
                                alert('JSON解析失败: ' + err.message);

                                // 如果解析失败，显示导入选项
                                showImportOptions(leftPanel, rightPanel);
                            }
                        } else {
                            // 尝试自动判断文件类型
                            try {
                                const jsonData = JSON.parse(content);
                                if (jsonData.roots) {
                                    parseBookmarksFile(content, leftPanel, rightPanel);
                                } else {
                                    saveBookmarks(jsonData);
                                    renderBookmarkFolders(jsonData, leftPanel, rightPanel);
                                    alert('JSON书签导入成功！');
                                }
                            } catch (error) {
                                // 如果不是JSON，尝试作为HTML解析
                                parseBookmarkHTML(content, leftPanel, rightPanel);
                            }
                        }
                    } catch (error) {
                        console.error('处理文件失败:', error);
                        alert('处理文件失败: ' + error.message);

                        // 如果处理失败，显示导入选项
                        showImportOptions(leftPanel, rightPanel);
                    }

                    // 移除文件输入元素
                    document.body.removeChild(fileInput);
                };

                reader.onerror = function() {
                    console.error('读取文件失败');
                    alert('读取文件失败，请重试');
                    document.body.removeChild(fileInput);

                    // 如果读取失败，显示导入选项
                    showImportOptions(leftPanel, rightPanel);
                };

                // 读取文件内容
                reader.readAsText(file);
            } else {
                // 用户未选择文件
                document.body.removeChild(fileInput);
            }
        });

        // 模拟点击以打开文件选择器
        fileInput.click();
    }

    // 在页面加载时创建悬浮按钮（使用window.onload确保执行）
    window.onload = function() {
        console.log('页面加载完成，当前设置：', settings);

        // 检测是否是Gitee网站，如果是则不创建悬浮按钮
        if (isGiteeSite()) {
            console.log('window.onload: 检测到Gitee网站，不创建悬浮按钮');
            return;
        }

        // 检测是否是视频播放器页面，如果是则不创建悬浮按钮
        if (isVideoPlayerSite()) {
            console.log('window.onload: 检测到视频播放器页面，不创建悬浮按钮');
            return;
        }

        // 从GM_getValue重新加载设置，确保使用最新值
        settings = loadSettings();
        console.log('重新加载设置:', settings);

        // 蓝奏云特殊处理 - 添加DOM监听以处理动态加载的内容
        if (isLanzouSite()) {
            console.log('蓝奏云网站onload特殊处理');

            // 首先清理所有可能的悬浮按钮
            const allButtons = document.querySelectorAll('.bookmarks-float-btn');
            if (allButtons.length > 0) {
                console.log('onload: 蓝奏云清理现有的' + allButtons.length + '个按钮');
                for (let i = 0; i < allButtons.length; i++) {
                    try {
                        allButtons[i].remove();
                    } catch (e) {}
                }
            }

            // 在蓝奏云页面创建新按钮前先对全局状态进行重置
            GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);

            // 添加DOM变化监听器，用于监测蓝奏云页面内容变化时可能出现的多余按钮
            const observer = new MutationObserver(function(mutations) {
                const buttons = document.querySelectorAll('.bookmarks-float-btn');

                if (buttons.length > 1) {
                    console.log('DOM变化检测到多个按钮，执行清理');
                    cleanupExtraButtons();
                }
            });

            // 开始观察document.body变化，包括子节点变化和子树变化
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });

            // 延迟一段时间再创建按钮，确保页面完全加载并处理了可能的框架
            setTimeout(function() {
                if (settings.floatButtonEnabled && document.querySelectorAll('.bookmarks-float-btn').length === 0) {
                    console.log('蓝奏云网站延迟创建按钮');
                    createFloatButton();
                }
            }, 1000);

            return; // 结束函数执行，不走后面的常规流程
        }

        // 普通网站的正常处理流程
        // 首先清理可能存在的多余按钮
        cleanupExtraButtons();

        // 检测DOM中是否已有按钮
        const existingButtons = document.querySelectorAll('.bookmarks-float-btn');
        if (existingButtons.length > 0) {
            console.log('页面中已存在悬浮按钮，不再创建');
            return;
        }

        // 获取全局按钮状态
        const globalBtnStatus = GM_getValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
        const btnTimestamp = GM_getValue(FLOAT_BTN_TIMESTAMP_KEY, 0);
        const now = Date.now();

        // 如果全局状态显示按钮存在且未过期，并且设置允许，不创建新按钮
        if (globalBtnStatus && (now - btnTimestamp < FLOAT_BTN_EXPIRE_TIME) && settings.floatButtonEnabled) {
            console.log('全局悬浮按钮状态显示已存在且未过期，不再创建新按钮');
        } else if (settings.floatButtonEnabled) {
            // 重置按钮状态并创建新按钮
            GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
            console.log('根据设置创建悬浮按钮');
            setTimeout(function() {
                createFloatButton();
            }, 500); // 稍微延迟创建，避免竞态条件
        } else {
            console.log('悬浮按钮已禁用，不创建');
        }
    };

    // 修改DOMContentLoaded事件处理，优化按钮创建逻辑
    window.addEventListener('DOMContentLoaded', function() {
        // 检测是否是Gitee网站，如果是则不创建悬浮按钮
        if (isGiteeSite()) {
            console.log('DOMContentLoaded: 检测到Gitee网站，不创建悬浮按钮');
            return;
        }

        // 检测是否是视频播放器页面，如果是则不创建悬浮按钮
        if (isVideoPlayerSite()) {
            console.log('DOMContentLoaded: 检测到视频播放器页面，不创建悬浮按钮');
            return;
        }

        // 蓝奏云特殊处理
        if (isLanzouSite()) {
            console.log('DOMContentLoaded: 蓝奏云特殊处理');

            // 蓝奏云网站在DOMContentLoaded阶段不创建按钮，等待onload事件
            return;
        }

        // 避免与window.onload重复创建按钮
        // 首先检查是否已有按钮存在
        if (document.querySelectorAll('.bookmarks-float-btn').length > 0) {
            console.log('DOMContentLoaded检测到已存在按钮，执行清理');
            cleanupExtraButtons();
            return;
        }

        // 检查全局状态
        const globalBtnStatus = GM_getValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
        if (globalBtnStatus) {
            console.log('全局状态显示按钮已存在，不在DOMContentLoaded中创建');
            return;
        }

        // 特殊检测：在iframe内不初始化按钮（尤其是蓝奏云）
        try {
            if (window.self !== window.top) {
                const currentDomain = window.location.hostname;
                if (currentDomain.includes('lanzou') || currentDomain.includes('lanzoui') ||
                    currentDomain.includes('lanzoux')) {
                    console.log('DOMContentLoaded: 检测到蓝奏云iframe，不创建按钮');
                    return;
                }
            }
        } catch (e) {
            console.error('DOMContentLoaded: 检测iframe失败', e);
        }

        // 延迟一小段时间创建按钮，避免与window.onload冲突
        setTimeout(() => {
            // 再次检查是否已有按钮
            if (document.querySelectorAll('.bookmarks-float-btn').length === 0 && settings.floatButtonEnabled) {
                console.log('DOMContentLoaded延迟检测无按钮，创建新按钮');
                createFloatButton();
            }
        }, 1500);
    });

    // 添加importFile函数到脚本中，如果尚未定义
    function importFile(accept, callback) {
        // 创建一个隐藏的文件输入元素
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = accept;
        fileInput.style.display = 'none';
        document.body.appendChild(fileInput);

        // 模拟点击以打开文件选择器
        fileInput.click();

        // 监听文件选择事件
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];
                const reader = new FileReader();

                reader.onload = function(e) {
                    const content = e.target.result;

                    try {
                        // 移除文件输入元素
                        document.body.removeChild(fileInput);

                        // 调用回调函数处理文件内容
                        callback(content);
                    } catch (error) {
                        console.error('处理文件失败:', error);
                        alert('处理文件失败: ' + error.message);
                    }
                };

                reader.onerror = function() {
                    console.error('读取文件失败');
                    alert('读取文件失败，请重试');
                    document.body.removeChild(fileInput);
                };

                // 读取文件内容
                reader.readAsText(file);
            } else {
                // 用户未选择文件
                document.body.removeChild(fileInput);
            }
        });
    }

    // 添加parseBookmarkHTML函数，如果尚未定义
    function parseBookmarkHTML(html, leftPanel, rightPanel) {
        try {
            // 创建临时文档解析HTML
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');

            // 初始化书签对象
            const bookmarks = {};
            bookmarks['导入的书签'] = [];
            bookmarks['未分组书签'] = [];

            // 查找所有书签文件夹和链接
            const dlElements = doc.querySelectorAll('dl');
            if (dlElements.length === 0) {
                throw new Error('未找到有效的书签数据');
            }

            // 递归处理书签树
            function processFolder(element, folderName) {
                const links = [];
                const children = element.children;

                for (let i = 0; i < children.length; i++) {
                    const child = children[i];

                    if (child.tagName === 'DT') {
                        // 检查是否是文件夹
                        const h3 = child.querySelector('h3') || child.querySelector('H3');
                        const subFolder = child.querySelector('dl') || child.querySelector('DL');

                        if (h3 && subFolder) {
                            // 这是一个子文件夹
                            const subFolderName = h3.textContent.trim();
                            processFolder(subFolder, subFolderName);
                        } else {
                            // 这是一个书签链接
                            const a = child.querySelector('a') || child.querySelector('A');
                            if (a) {
                                const url = a.getAttribute('href');
                                const title = a.textContent.trim() || '未命名书签';

                                // 添加书签，不直接处理图标URL，交给createFaviconElement处理
                                links.push({
                                    title: title,
                                    url: url,
                                    favicon: '' // 留空，由createFaviconElement函数处理
                                });
                            }
                        }
                    }
                }

                // 保存文件夹中的链接
                if (links.length > 0) {
                    if (!bookmarks[folderName]) {
                        bookmarks[folderName] = [];
                    }
                    bookmarks[folderName] = bookmarks[folderName].concat(links);
                }
            }

            // 处理根文件夹
            processFolder(dlElements[0], '导入的书签');

            // 保存书签到本地存储
            saveBookmarks(bookmarks);

            // 显示书签
            renderBookmarkFolders(bookmarks, leftPanel, rightPanel);
            alert('HTML书签导入成功！');

        } catch (error) {
            console.error('解析HTML书签失败:', error);
            alert('解析HTML书签失败: ' + error.message);
        }
    }

    // 添加parseBookmarksFile函数，如果尚未定义
    function parseBookmarksFile(content, leftPanel, rightPanel) {
        try {
            // 尝试解析JSON内容
            const data = JSON.parse(content);

            // 检查是否是Chrome/Edge书签文件格式
            if (data.roots) {
                // 初始化书签对象
                const bookmarks = {};

                // 处理书签栏
                if (data.roots.bookmark_bar && data.roots.bookmark_bar.children) {
                    processBookmarkNodes(data.roots.bookmark_bar.children, '书签栏', bookmarks);
                }

                // 处理其他书签
                if (data.roots.other && data.roots.other.children) {
                    processBookmarkNodes(data.roots.other.children, '其他书签', bookmarks);
                }

                // 处理同步书签
                if (data.roots.synced && data.roots.synced.children) {
                    processBookmarkNodes(data.roots.synced.children, '同步的书签', bookmarks);
                }

                // 保存书签到本地存储
                saveBookmarks(bookmarks);

                // 显示书签
                renderBookmarkFolders(bookmarks, leftPanel, rightPanel);
                alert('Bookmarks文件导入成功！');

            } else {
                throw new Error('无效的Bookmarks文件格式');
            }
        } catch (error) {
            console.error('解析Bookmarks文件失败:', error);
            alert('解析Bookmarks文件失败: ' + error.message);
        }
    }

    // 添加processBookmarkNodes辅助函数
    function processBookmarkNodes(nodes, folderName, bookmarksObj) {
        if (!bookmarksObj[folderName]) {
            bookmarksObj[folderName] = [];
        }

        for (let node of nodes) {
            if (node.type === 'folder' && node.children) {
                // 这是一个文件夹
                const subFolderName = node.name || '未命名文件夹';
                processBookmarkNodes(node.children, subFolderName, bookmarksObj);
            } else if (node.type === 'url') {
                // 这是一个书签
                bookmarksObj[folderName].push({
                    title: node.name || '未命名书签',
                    url: node.url,
                    favicon: '' // 留空，由createFaviconElement函数处理
                });
            }
        }
    }

    // 添加导出为JSON功能
    function exportBookmarksAsJson(bookmarks) {
        try {
            // 创建Blob对象
            const jsonString = JSON.stringify(bookmarks, null, 2);
            const blob = new Blob([jsonString], { type: 'application/json' });

            // 创建下载链接
            const downloadLink = document.createElement('a');
            downloadLink.href = URL.createObjectURL(blob);
            downloadLink.download = 'bookmarks_export.json';
            downloadLink.style.display = 'none';

            // 添加到文档中并触发点击
            document.body.appendChild(downloadLink);
            downloadLink.click();

            // 清理
            setTimeout(() => {
                document.body.removeChild(downloadLink);
                URL.revokeObjectURL(downloadLink.href);
            }, 100);

            return true;
        } catch (error) {
            console.error('导出书签失败:', error);
            alert('导出书签失败: ' + error.message);
            return false;
        }
    }

    // 添加使面板可拖动的函数
    function makeDraggable(element, handle) {
        let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

        if (handle) {
            // 如果指定了拖动手柄
            handle.style.cursor = 'move';
            handle.onmousedown = dragMouseDown;
        } else {
            // 否则整个元素可拖动
            element.onmousedown = dragMouseDown;
        }

        function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();

            // 如果元素已经被拖动过，记录其当前位置
            if (!element.style.transform || element.style.transform === 'none') {
                // 只有在第一次拖动时执行
                if (element.style.top === '50%' && element.style.left === '50%') {
                    // 获取当前实际位置
                    const rect = element.getBoundingClientRect();
                    element.style.top = rect.top + 'px';
                    element.style.left = rect.left + 'px';
                    // 移除translate变换
                    element.style.transform = 'none';
                }
            }

            // 获取鼠标位置
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            // 鼠标移动时调用函数
            document.onmousemove = elementDrag;
        }

        function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            // 计算新位置
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;

            // 设置元素的新位置
            element.style.top = (element.offsetTop - pos2) + "px";
            element.style.left = (element.offsetLeft - pos1) + "px";
        }

        function closeDragElement() {
            // 停止移动
            document.onmouseup = null;
            document.onmousemove = null;
        }
    }

    // 添加滚动修复函数
    function fixScrollingIssues() {
        // 获取内容容器
        const contentContainer = document.getElementById('bookmarks-container-content');
        const leftPanel = document.querySelector('.bookmarks-left-panel');
        const rightPanel = document.querySelector('.bookmarks-right-panel');

        // 确保内容容器可以滚动
        if (contentContainer) {
            contentContainer.style.overflowY = 'auto';
            contentContainer.style.WebkitOverflowScrolling = 'touch';
        }

        // 确保左侧面板可以滚动
        if (leftPanel) {
            leftPanel.style.overflowY = 'auto';
            leftPanel.style.WebkitOverflowScrolling = 'touch';
        }

        // 确保右侧面板可以滚动
        if (rightPanel) {
            rightPanel.style.overflowY = 'auto';
            rightPanel.style.WebkitOverflowScrolling = 'touch';
        }
    }

    // 添加搜索功能
    function performSearch(query, resultsContainer, bookmarks, leftPanel, rightPanel) {
        // 清空结果容器
        resultsContainer.innerHTML = '';

        // 如果查询为空，不执行搜索
        if (!query) {
            return;
        }

        // 用于存储搜索结果
        const results = [];
        const lowerQuery = query.toLowerCase();

        // 搜索所有书签
        for (const folderName in bookmarks) {
            const folderItems = bookmarks[folderName];

            if (!folderItems || !Array.isArray(folderItems)) continue;

            for (const bookmark of folderItems) {
                // 检查标题和URL
                if (bookmark.title.toLowerCase().includes(lowerQuery) ||
                    bookmark.url.toLowerCase().includes(lowerQuery)) {
                    results.push({
                        title: bookmark.title,
                        url: bookmark.url,
                        favicon: bookmark.favicon,
                        folder: folderName
                    });

                    // 限制最大结果数量
                    if (results.length >= 20) break;
                }
            }

            // 如果已经找到足够多的结果，跳出循环
            if (results.length >= 20) break;
        }

        // 显示搜索结果
        if (results.length > 0) {
            results.forEach(result => {
                const resultItem = document.createElement('div');
                resultItem.className = 'bookmarks-search-result-item';

                // 图标
                const iconElement = createFaviconElement(result.url);
                iconElement.className = 'bookmarks-search-result-icon';
                resultItem.appendChild(iconElement);

                // 标题
                const titleSpan = document.createElement('span');
                titleSpan.className = 'bookmarks-search-result-title';
                titleSpan.textContent = result.title;
                resultItem.appendChild(titleSpan);

                // 文件夹
                const folderSpan = document.createElement('span');
                folderSpan.className = 'bookmarks-search-result-folder';
                folderSpan.textContent = result.folder;
                resultItem.appendChild(folderSpan);

                // 点击事件
                resultItem.addEventListener('click', function(e) {
                    // 阻止冒泡
                    e.stopPropagation();

                    // 打开URL
                    window.open(result.url, '_blank');

                    // 隐藏搜索结果
                    resultsContainer.style.display = 'none';
                });

                resultsContainer.appendChild(resultItem);
            });
        } else {
            // 无搜索结果
            const noResult = document.createElement('div');
            noResult.className = 'bookmarks-search-no-result';
            noResult.textContent = '无匹配结果';
            resultsContainer.appendChild(noResult);
        }

        // 确保滚动正常工作
        resultsContainer.style.overflowY = 'auto';
        resultsContainer.style.pointerEvents = 'auto';

        // 通过特别函数修复滚动问题
        setTimeout(() => fixSearchResultsScrolling(), 0);
    }

    // 添加设置模态框
    function showSettingsModal(container) {
        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'bookmarks-import-modal';
        modal.style.maxWidth = '480px';

        // 模态框内容
        modal.innerHTML = `
            <h3 style="text-align: left; margin-bottom: 20px;">设置</h3>
            <div class="settings-section" style="text-align: left;">
                <div class="settings-item" style="margin-bottom: 16px;">
                    <div class="settings-label" style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div class="settings-title" style="font-weight: 600; font-size: 15px; margin-bottom: 4px;">启用悬浮按钮</div>
                            <div class="settings-description" style="color: #666; font-size: 13px;">在页面左侧显示一个悬浮按钮，用于快速打开书签分组</div>
                        </div>
                        <label class="switch">
                            <input type="checkbox" id="float-btn-toggle" ${settings.floatButtonEnabled ? 'checked' : ''}>
                            <span class="slider round"></span>
                        </label>
                    </div>
                </div>

                <div class="settings-item" style="margin-bottom: 16px;">
                    <div class="settings-label" style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div class="settings-title" style="font-weight: 600; font-size: 15px; margin-bottom: 4px;">自动隐藏延迟 (毫秒)</div>
                            <div class="settings-description" style="color: #666; font-size: 13px;">设置悬浮按钮自动隐藏的时间</div>
                        </div>
                        <div>
                            <input type="number" id="auto-hide-delay" value="${settings.autoHideDelay}" min="500" max="10000" step="500" style="width: 80px; padding: 5px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; text-align: center; box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);">
                        </div>
                    </div>
                </div>

                <div class="settings-item" style="margin-bottom: 16px;">
                    <div class="settings-label" style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div class="settings-title" style="font-weight: 600; font-size: 15px; margin-bottom: 4px;">启用自动备份</div>
                            <div class="settings-description" style="color: #666; font-size: 13px;">定期备份书签数据，防止数据丢失</div>
                        </div>
                        <label class="switch">
                            <input type="checkbox" id="backup-toggle" ${settings.enableBackup !== false ? 'checked' : ''}>
                            <span class="slider round"></span>
                        </label>
                    </div>
                </div>

                <div class="settings-item" id="backup-operations" style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee;">
                    <div style="margin-bottom: 12px;">
                        <div class="settings-title" style="font-weight: 600; font-size: 15px; margin-bottom: 4px;">数据管理</div>
                        <div class="settings-description" style="color: #666; font-size: 13px; margin-bottom: 10px;">备份、恢复和修复书签数据</div>
                        <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                            <button id="backup-now-btn" style="flex: 1; padding: 8px 10px; background-color: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; white-space: nowrap;">立即备份</button>
                            <button id="restore-backup-btn" style="flex: 1; padding: 8px 10px; background-color: #f5f5f5; border: 1px solid #ddd; color: #333; border-radius: 4px; cursor: pointer; font-size: 13px; white-space: nowrap;">从备份恢复</button>
                            <button id="repair-storage-btn" style="flex: 1; padding: 8px 10px; background-color: #f5f5f5; border: 1px solid #ddd; color: #333; border-radius: 4px; cursor: pointer; font-size: 13px; white-space: nowrap;">修复存储</button>
                            <button id="clear-backup-btn" style="flex: 1; padding: 8px 10px; background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; border-radius: 4px; cursor: pointer; font-size: 13px; white-space: nowrap;">清除备份</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bookmarks-import-btns" style="display: flex; justify-content: flex-end; margin-top: 24px; gap: 10px;">
                <button class="bookmarks-import-btn bookmarks-import-cancel" style="padding: 8px 16px; background-color: #f5f5f5; border: 1px solid #ddd; color: #333; border-radius: 4px; cursor: pointer; font-size: 14px;">取消</button>
                <button class="bookmarks-import-btn bookmarks-import-confirm" style="padding: 8px 16px; background-color: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;">保存</button>
            </div>

            <style>
                .switch {
                    position: relative;
                    display: inline-block;
                    width: 46px;
                    height: 24px;
                }

                .switch input {
                    opacity: 0;
                    width: 0;
                    height: 0;
                }

                .slider {
                    position: absolute;
                    cursor: pointer;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: #ccc;
                    transition: .4s;
                }

                .slider:before {
                    position: absolute;
                    content: "";
                    height: 18px;
                    width: 18px;
                    left: 3px;
                    bottom: 3px;
                    background-color: white;
                    transition: .4s;
                }

                input:checked + .slider {
                    background-color: #1a73e8;
                }

                input:focus + .slider {
                    box-shadow: 0 0 1px #1a73e8;
                }

                input:checked + .slider:before {
                    transform: translateX(22px);
                }

                .slider.round {
                    border-radius: 24px;
                }

                .slider.round:before {
                    border-radius: 50%;
                }
            </style>
        `;

        container.appendChild(modal);

        // 阻止事件冒泡
        modal.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 获取元素
        const floatBtnToggle = modal.querySelector('#float-btn-toggle');
        const autoHideDelay = modal.querySelector('#auto-hide-delay');
        const backupToggle = modal.querySelector('#backup-toggle');
        const backupNowBtn = modal.querySelector('#backup-now-btn');
        const restoreBackupBtn = modal.querySelector('#restore-backup-btn');
        const repairStorageBtn = modal.querySelector('#repair-storage-btn');
        const clearBackupBtn = modal.querySelector('#clear-backup-btn');
        const confirmBtn = modal.querySelector('.bookmarks-import-confirm');
        const cancelBtn = modal.querySelector('.bookmarks-import-cancel');

        // 立即备份按钮事件
        backupNowBtn.addEventListener('click', function() {
            const bookmarks = loadStoredBookmarks();
            if (Object.keys(bookmarks).length > 0) {
                GM_setValue(BOOKMARKS_BACKUP_KEY, bookmarks);
                // 更新备份时间
                GM_setValue(LAST_SAVE_TIME_KEY, Date.now().toString());
                alert('书签数据已成功备份！');
            } else {
                alert('没有找到可以备份的书签数据！');
            }
        });

        // 从备份恢复按钮事件
        restoreBackupBtn.addEventListener('click', function() {
            const backupBookmarks = GM_getValue(BOOKMARKS_BACKUP_KEY);
            if (backupBookmarks) {
                try {
                    if (isValidBookmarks(backupBookmarks)) {
                        if (confirm('确定要从备份恢复书签数据吗？当前数据将被覆盖。')) {
                            // 保存到主存储
                            GM_setValue(BOOKMARKS_KEY, backupBookmarks);

                            // 立即关闭设置模态框
                            modal.remove();

                            // 获取当前书签面板容器
                            const bookmarksContainer = document.querySelector('.bookmarks-group-container');
                            if (bookmarksContainer) {
                                // 获取左右面板
                                const leftPanel = bookmarksContainer.querySelector('.bookmarks-left-panel');
                                const rightPanel = bookmarksContainer.querySelector('.bookmarks-right-panel');

                                if (leftPanel && rightPanel) {
                                    // 清空面板
                                    leftPanel.innerHTML = '';
                                    rightPanel.innerHTML = '';

                                    // 重新渲染书签
                                    renderBookmarkFolders(backupBookmarks, leftPanel, rightPanel);

                                    // 显示成功提示
                                    alert('书签数据已从备份恢复并显示！');
                                } else {
                                    // 没有找到面板，刷新整个书签组界面
                                    bookmarksContainer.remove();
                                    setTimeout(() => {
                                        createBookmarksGroup();
                                        alert('书签数据已从备份恢复！');
                                    }, 100);
                                }
                            } else {
                                // 书签面板不存在，创建新的
                                setTimeout(() => {
                                    createBookmarksGroup();
                                    alert('书签数据已从备份恢复！');
                                }, 100);
                            }
                        }
                    } else {
                        alert('备份数据无效，无法恢复！');
                    }
                } catch (e) {
                    alert('恢复备份失败: ' + e.message);
                }
            } else {
                alert('没有找到可用的备份数据！');
            }
        });

        // 修复存储按钮事件
        repairStorageBtn.addEventListener('click', function() {
            if (confirm('此操作将尝试修复可能损坏的书签数据。继续？')) {
                const repairResult = repairBookmarksStorage();
                if (repairResult) {
                    // 获取修复后的书签数据
                    const repairedData = loadStoredBookmarks();

                    // 关闭设置模态框
                    modal.remove();

                    // 重新加载书签界面
                    const container = document.querySelector('.bookmarks-group-container');
                    if (container) {
                        const leftPanel = container.querySelector('.bookmarks-left-panel');
                        const rightPanel = container.querySelector('.bookmarks-right-panel');

                        if (leftPanel && rightPanel) {
                            // 清空面板
                            leftPanel.innerHTML = '';
                            rightPanel.innerHTML = '';

                            // 重新渲染书签
                            renderBookmarkFolders(repairedData, leftPanel, rightPanel);
                            alert('修复完成并已重新加载！');
                        } else {
                            // 如果找不到面板，重新创建
                            container.remove();
                            setTimeout(createBookmarksGroup, 100);
                            alert('修复完成！已重新加载书签界面。');
                        }
                    } else {
                        // 如果没有找到容器，创建新的
                        setTimeout(createBookmarksGroup, 100);
                        alert('修复完成！已重新加载书签界面。');
                    }
                } else {
                    alert('修复未能找到有效数据。请尝试重新导入书签。');
                }
            }
        });

        // 清除备份按钮事件
        clearBackupBtn.addEventListener('click', function() {
            if (confirm('此操作将清除所有备份数据。继续？')) {
                // 增加二次确认，要求用户输入特定文字
                const userInput = prompt('请输入"确认"两个字以清除备份数据');
                if (userInput === '确认') {
                    // 清空备份数据
                    GM_deleteValue(BOOKMARKS_BACKUP_KEY);
                    GM_deleteValue(LAST_SAVE_TIME_KEY);
                    alert('备份数据已成功清除！');
                } else {
                    alert('操作已取消');
                }
            }
        });

        // 取消按钮
        cancelBtn.addEventListener('click', function() {
            modal.remove();
        });

        // 确认按钮
        confirmBtn.addEventListener('click', function() {
            // 更新设置
            settings.floatButtonEnabled = floatBtnToggle.checked;
            settings.autoHideDelay = parseInt(autoHideDelay.value) || 3000;
            settings.enableBackup = backupToggle.checked;

            // 保存设置
            saveSettings(settings);

            // 应用设置变更
            const existingBtn = document.querySelector('.bookmarks-float-btn');
            if (existingBtn) {
                existingBtn.remove();
            }

            if (settings.floatButtonEnabled) {
                createFloatButton();
            }

            // 关闭模态框
            modal.remove();

            // 提示保存成功
            alert('设置已保存');
        });
    }

    // 添加修复存储的功能
    function repairBookmarksStorage() {
        try {
            // 尝试从所有可能的来源加载书签数据
            let bookmarks = null;
            let source = '';

            // 检查主存储
            try {
                const mainData = GM_getValue(BOOKMARKS_KEY);
                if (mainData) {
                    if (isValidBookmarks(mainData)) {
                        bookmarks = mainData;
                        source = '主存储';
                    }
                }
            } catch (e) {
                console.error('读取主存储失败:', e);
            }

            // 检查备份
            if (!bookmarks) {
                try {
                    const backupData = GM_getValue(BOOKMARKS_BACKUP_KEY);
                    if (backupData) {
                        if (isValidBookmarks(backupData)) {
                            bookmarks = backupData;
                            source = '备份';
                        }
                    }
                } catch (e) {
                    console.error('读取备份失败:', e);
                }
            }

            // 检查传统存储（兼容旧版本）
            if (!bookmarks) {
                try {
                    const legacyStr = localStorage.getItem('userBookmarks');
                    if (legacyStr) {
                        const legacyData = JSON.parse(legacyStr);
                        if (isValidBookmarks(legacyData)) {
                            bookmarks = legacyData;
                            source = '传统存储';
                        }
                    }
                } catch (e) {
                    console.error('读取传统存储失败:', e);
                }
            }

            // 如果找到有效数据，保存到所有位置
            if (bookmarks) {
                try {
                    GM_setValue(BOOKMARKS_KEY, bookmarks);
                    GM_setValue(BOOKMARKS_BACKUP_KEY, bookmarks);

                    // 更新备份时间
                    GM_setValue(LAST_SAVE_TIME_KEY, Date.now().toString());

                    console.log(`已从${source}恢复并修复数据，总文件夹数: ${Object.keys(bookmarks).length}`);
                    return true;
                } catch (e) {
                    console.error('保存修复后的数据失败:', e);

                    // 尝试清理部分数据然后再保存
                    try {
                        // 只保留前5个文件夹的数据以减小大小
                        const folderNames = Object.keys(bookmarks);
                        if (folderNames.length > 5) {
                            const reducedBookmarks = {};
                            for (let i = 0; i < 5; i++) {
                                reducedBookmarks[folderNames[i]] = bookmarks[folderNames[i]];
                            }

                            GM_setValue(BOOKMARKS_KEY, reducedBookmarks);
                            GM_setValue(BOOKMARKS_BACKUP_KEY, reducedBookmarks);

                            console.log('数据过大，已保存部分数据（前5个文件夹）');
                            return true;
                        }
                    } catch (e2) {
                        console.error('保存精简数据失败:', e2);
                    }
                }
            } else {
                console.warn('未找到有效的书签数据用于修复');
            }

            return false;
        } catch (error) {
            console.error('修复存储失败:', error);
            return false;
        }
    }

    // 在页面卸载时清除按钮状态
    window.addEventListener('unload', function() {
        // 移除全局按钮状态
        GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
    });

    // 页面可见性变化时检查按钮状态
    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'visible') {
            // 检测是否是视频播放器页面，如果是则不创建悬浮按钮
            if (isVideoPlayerSite()) {
                console.log('页面可见性变化: 检测到视频播放器页面，不创建悬浮按钮');
                return;
            }

            // 页面变为可见时检查按钮状态
            const buttons = document.querySelectorAll('.bookmarks-float-btn');
            if (buttons.length > 1) {
                cleanupExtraButtons();
            } else if (buttons.length === 1 && document.body.contains(buttons[0])) {
                // 更新时间戳
                GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, true);
                GM_setValue(FLOAT_BTN_TIMESTAMP_KEY, Date.now());
            } else if (buttons.length === 0 && settings.floatButtonEnabled) {
                // 没有按钮但应该有，检查全局状态
                const globalStatus = GM_getValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
                const btnTimestamp = GM_getValue(FLOAT_BTN_TIMESTAMP_KEY, 0);
                const now = Date.now();

                // 如果全局状态为false或者时间戳已过期，创建新按钮
                if (!globalStatus || (now - btnTimestamp >= FLOAT_BTN_EXPIRE_TIME)) {
                    console.log('页面可见性变化检测：需要创建新按钮');
                    createFloatButton();
                }
            }
        }
    });

    // 清除本地存储中的旧数据，完全迁移到GM存储
    function clearLocalStorageData() {
        try {
            localStorage.removeItem(BOOKMARKS_KEY);
            localStorage.removeItem(BOOKMARKS_BACKUP_KEY);
            localStorage.removeItem(LAST_SAVE_TIME_KEY);
            localStorage.removeItem(SETTINGS_KEY);
            localStorage.removeItem('bookmarkPositions');
            localStorage.removeItem('lastRemoteUrl');
            localStorage.removeItem('lastSelectedFolder');
            localStorage.removeItem('userBookmarks');
            localStorage.removeItem(GLOBAL_FLOAT_BTN_STATUS_KEY);
            localStorage.removeItem(FLOAT_BTN_TIMESTAMP_KEY);
            console.log('已清除本地存储中的旧数据');
        } catch (e) {
            console.error('清除本地存储数据失败:', e);
        }
    }

    // 执行清理，只需运行一次
    setTimeout(clearLocalStorageData, 2000);

    // 清理多余的悬浮按钮 - 完善该函数
    function cleanupExtraButtons() {
        const buttons = document.querySelectorAll('.bookmarks-float-btn');
        if (buttons.length > 1) {
            console.log(`检测到${buttons.length}个悬浮按钮，保留第一个，清理其余按钮`);
            for (let i = 1; i < buttons.length; i++) {
                try {
                    buttons[i].remove();
                    console.log(`已移除第${i+1}个悬浮按钮`);
                } catch (e) {
                    console.error(`移除第${i+1}个悬浮按钮失败:`, e);
                }
            }

            // 更新按钮状态信息
            if (buttons.length > 0 && document.body.contains(buttons[0])) {
                GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, true);
                GM_setValue(FLOAT_BTN_TIMESTAMP_KEY, Date.now());
                console.log('更新了全局按钮状态为true');
            } else {
                GM_setValue(GLOBAL_FLOAT_BTN_STATUS_KEY, false);
                console.log('更新了全局按钮状态为false');
            }
        }
    }

    // 特别针对搜索结果容器的滚动修复
    function fixSearchResultsScrolling() {
        const searchResults = document.querySelector('.bookmarks-search-results');
        if (!searchResults) return;

        console.log('修复搜索结果容器滚动');

        // 确保样式正确
        searchResults.style.overflowY = 'auto';
        searchResults.style.pointerEvents = 'auto';
        searchResults.style.webkitOverflowScrolling = 'touch';
        searchResults.style.overscrollBehavior = 'contain';

        // 添加专用滚轮事件处理
        searchResults.addEventListener('wheel', function(e) {
            // 检查是否可以继续滚动
            const canScrollDown = this.scrollTop + this.clientHeight < this.scrollHeight;
            const canScrollUp = this.scrollTop > 0;

            // 只有在边界情况下才阻止默认行为
            if ((e.deltaY > 0 && !canScrollDown) || (e.deltaY < 0 && !canScrollUp)) {
                e.preventDefault();
            }

            // 阻止冒泡到父元素
            e.stopPropagation();
        }, { passive: false, capture: true });
    }

    // 处理搜索结果滚动
    function handleSearchResultsScrolling() {
        const searchResults = document.querySelector('.bookmarks-search-results');
        if (!searchResults) return;

        console.log('处理搜索结果滚动');

        // 添加滚动事件处理
        searchResults.addEventListener('scroll', function() {
            // 检查是否到达底部
            if (this.scrollTop + this.clientHeight >= this.scrollHeight) {
                console.log('搜索结果已滚动到底部');
                // 在这里添加加载更多搜索结果的逻辑
            }
        });
    }

    // 在页面完全加载后检测并清理视频播放器页面上的悬浮按钮
    window.addEventListener('load', function() {
        // 首次检测和清理
        checkAndCleanVideoPlayerButtons();

        // 定期检测和清理 - 每2秒检测一次，持续30秒
        let checkCount = 0;
        const maxChecks = 15; // 15次 × 2秒 = 30秒

        const intervalId = setInterval(function() {
            checkCount++;
            checkAndCleanVideoPlayerButtons();

            // 检测到一定次数后停止
            if (checkCount >= maxChecks) {
                clearInterval(intervalId);
            }
        }, 2000);

        // DOM变化监听，检测视频元素动态添加
        const observer = new MutationObserver(function(mutations) {
            // 当DOM发生变化时检测是否有新的视频元素
            for (const mutation of mutations) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    // 检查是否添加了视频相关元素
                    for (const node of mutation.addedNodes) {
                        if (node.nodeName === 'VIDEO' ||
                            (node.nodeType === Node.ELEMENT_NODE &&
                             (node.querySelector('video') ||
                              node.classList.contains('player') ||
                              node.id?.includes('player')))) {
                            // 发现视频元素，立即清理
                            checkAndCleanVideoPlayerButtons();
                            return;
                        }
                    }
                }
            }
        });

        // 开始观察document.body的所有子节点变化
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        // 30秒后停止监听
        setTimeout(function() {
            observer.disconnect();
        }, 30000);
    });

    // 视频播放器按钮检测和清理函数
    function checkAndCleanVideoPlayerButtons() {
        try {
            if (typeof isVideoPlayerSite === 'function' && isVideoPlayerSite()) {
                console.log('检测到视频播放器页面，清理所有悬浮按钮');
                const buttons = document.querySelectorAll('.bookmarks-float-btn');
                if (buttons.length > 0) {
                    for (let i = 0; i < buttons.length; i++) {
                        try {
                            buttons[i].remove();
                            console.log('已移除视频播放器页面上的悬浮按钮');
                        } catch (e) {
                            console.error('移除按钮失败:', e);
                        }
                    }

                    // 重置全局按钮状态
                    if (typeof GM_setValue === 'function') {
                        GM_setValue('globalFloatBtnStatus', false);
                    }
                }
            }
        } catch (e) {
            console.error('检测和清理按钮时出错:', e);
        }
    }

    // 添加菜单命令
    GM_registerMenuCommand('显示书签分组', createBookmarksGroup);
    GM_registerMenuCommand('悬浮按钮设置', () => {
        // 创建一个临时容器来显示设置模态框
        const tempContainer = document.createElement('div');
        tempContainer.className = 'bookmarks-group-container';
        tempContainer.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        document.body.appendChild(tempContainer);

        showSettingsModal(tempContainer);

        // 点击外部区域关闭设置
        tempContainer.addEventListener('click', function(e) {
            if (e.target === tempContainer) {
                tempContainer.remove();
            }
        });
    });
})();